Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create the object of Runnable being it interface

Tags:

java

I see a sample code where in new Runnable() is used and it is anonymous inner class .

Runnable runnable = new Runnable() {
public void run() {
int option = (int) (Math.random() * 4);
switch (option) {
case 0: x.a(); break;
case 1: x.b(); break;
case 2: y.a(); break;
case 3: y.b(); break;
}
}
};

Any help is appreciated . I am new to this .

like image 245
Srilekha Avatar asked Sep 27 '15 07:09

Srilekha


2 Answers

Yes. We can. That's called as Anonymous inner class. Not only Runnable but you can create for any Interface anonymously.

Recommending to read this

https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

like image 116
Suresh Atta Avatar answered Sep 23 '22 00:09

Suresh Atta


I would like to add something here to make things more clear.
We can never instantiate an interface in java. We can, however, refer to an object that implements an interface by the type of the interface.

In the code you shared,we are creating an anonymous class which implements that interface.We are creating an object of anonymous type,not of interface Runnable.

public class RunnableImpl implements Runnable{
 ...
}

public static void main(String[] args)
{
    Runnable runnable = new RunnableImpl();
    //Runnable test = new Runnable(); // wont compile
}

See Also

  • Can we create an instance of an interface in Java?
like image 30
Prince Avatar answered Sep 25 '22 00:09

Prince