-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.

1
  • 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 for more. Commented May 31, 2019 at 2:21

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.