Can we create a Runnable object that is its interface

I see an example code that uses the new Runnable (), and this is an anonymous inner class.

Runnable runnable = new Runnable() { public void run() { int option = (int) (Math.random() * 4); switch (option) { case 0: xa(); break; case 1: xb(); break; case 2: ya(); break; case 3: yb(); break; } } }; 

Any help is appreciated. I am new to this.

+6
source share
2 answers

Yes. We can. This is called an anonymous inner class. Not only Runnable , but you can create for any Interface anonymously.

Recommended to read this.

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

+4
source

I would like to add something here to make things clearer.
We can never create an interface in java. However, we can refer to an object that implements an interface by type of interface.

In the code you shared, we create an anonymous class that implements this interface. We create an object of an anonymous type, not a Runnable interface.

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

see also

+2
source

All Articles