我们可以创建Runnable的对象作为它的接口

时间:2021-06-03 20:51:48

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

我看到一个示例代码,其中使用了新的Runnable(),它是匿名内部类。

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 .

任何帮助表示赞赏。我是新来的 。

2 个解决方案

#1


4  

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

#2


2  

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.

我想在这里添加一些东西以使事情更清楚。我们永远无法在java中实例化接口。但是,我们可以参考通过接口类型实现接口的对象。

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.

在您共享的代码中,我们创建了一个实现该接口的匿名类。我们正在创建一个匿名类型的对象,而不是接口Runnable。

public class RunnableImpl implements Runnable{
 ...
}

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

See Also

#1


4  

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

#2


2  

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.

我想在这里添加一些东西以使事情更清楚。我们永远无法在java中实例化接口。但是,我们可以参考通过接口类型实现接口的对象。

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.

在您共享的代码中,我们创建了一个实现该接口的匿名类。我们正在创建一个匿名类型的对象,而不是接口Runnable。

public class RunnableImpl implements Runnable{
 ...
}

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

See Also