-1

While creating threads I see code like:-

Runnable watdaheck = new Runnable()
{
System.out.println("java with time contradicts itself");
}

From what I know an interface cannot be instantiated so I fail to understand how we can write Runnable() for creating anonymous class. An interface can be given a reference but cannot be instantiated is what we are taught in polymorphism.

Prabhat Gaur
  • 146
  • 1
  • 10
  • 1
    Note that the thing that's like an interface but that you can instantiate is a _class_, not an object. I think you meant to ask if Runnable is an interface or a class. See [this question](https://stackoverflow.com/questions/9224517/what-are-classes-references-and-objects/9224971) for more. – yshavit May 31 '19 at 02:21

3 Answers3

6

Runnable is interface, you are creating an anonymous class which implements the Runnable interface.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
xingbin
  • 27,410
  • 9
  • 53
  • 103
2

I just modify a bit your code.

 Runnable watdaheck = new Runnable()
    {    
         public void run(){
             System.out.println("java with time contradicts itself");
         }
    }

The right part

new Runnable()
    {    
         public void run(){
             System.out.println("java with time contradicts itself");
         }
    }

is an instance of an anonymous class that implements interface Runnable The left part Runnable watdaheck, watdaheck is a reference that refers to above object. Your code is same with below code:

class SubRunnable implements Runnable{
   public void run(){
       //do something
   }
}
Runnable r = new SubRunnable();

You should read more about anonymous class in Java. https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

TaQuangTu
  • 2,155
  • 2
  • 16
  • 30
1

Runnable is an interface. We use it with the "new" operator in order to create an anonymous class object whICH

Rishabh Ritweek
  • 550
  • 3
  • 10