Home > Back-end >  Runnable interface instantiation
Runnable interface instantiation

Time:05-02

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.

CodePudding user response:

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.

CodePudding user response:

in OOP call that polymorphism.
it say you can for instantiating from classB (assume ClassB is subclass of ClassA) decelerate variable with ClassA type, and then instantiating from ClassB and assign it to that variable.
for example in java Object class is root of any classes so you can do it like below:

Object x = new YourClass();

or if for example your class implements InterfaceA you can do it like here:

InterfaceA x = new YourClass();
  • Related