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 .
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With