Skip to content
Advertisement

Runnable interface instantiation

I am following the book Head first java and was reading about threads and came to know about the Runnable interface. Now we know an interface can’t be instantiated directly. Its members are implemented by any class that implements the interface , but below code made bouncers over my head. The book declares the instance of the Runnable interface and assign the object of the implementing class of the runnable interface.

public class MyRunnable implements Runnable {
   public void main() {
        go();
   }
   public void go() {
        doMore();
   }
   public void doMore() {
     System.out.println("top of the stack");
   }
}

class ThreadTester {
   public static void main(String[] args) {
      Runnable threadJob = new MyRunnable();
      Thread myThread = new Thread(threadJob);
      myThread.start();
      System.out.println("back in pain");
  }
}

I couldn’t understand the line Runnable threadJob = new MyRunnable(); . How an interface being instantiated when it is not allowed. Why can’t be the line like MyRunnable threadJob = new MyRunnable(); . I mean MyRunnable class passes the IS-A test for Runnable interface so why author chose the former statement. Is that something I am missing here. Please help me clarify.

Advertisement

Answer

Now we know an interface can’t be instantiated directly.

You’re not instantiating the Runnable interface directly.

Hopefully you agree that the following should work:

MyRunnable threadJob = new MyRunnable();
Runnable runnable = threadJob; // since threadJob is a Runnable

So why shouldn’t that line work?

When we say that you can’t instantiate an interface directly, what that means is that you can’t write

Runnable runnable = new Runnable();

That’s the only thing that doesn’t work.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement