英文:
What is the difference between creating an object with superclass reference and creating an object with subclass reference?
问题
以下是要翻译的代码部分:
class C implements Runnable{
public void run() {
for(int i=0;i<5;i++) {
System.out.println("Thread2");
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
}
}
然后在我的主线程中,我写下:
C c = new C();
它产生的输出与以下代码相同:
Runnable c=new C();
关于它们各自的优点以及何时使用哪一个,有没有通用的规则呢?
英文:
Here's a snippet of my code:
class C implements Runnable{
public void run() {
for(int i=0;i<5;i++) {
System.out.println("Thread2");
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
}
}
Then in my main thread, I write:
C c = new C();
which produces the same output as
Runnable c=new C();
What are the advantages of using either of them?
Is there a general rule when to use which one?
答案1
得分: 1
对于C c = new C()
,变量的类型是C
类型,而对于Runnable c = new C()
,变量的类型是Runnable
。对于第一种情况,只能存储C
类型的实例在变量中。对于第二种情况,允许存储实现了Runnable
接口的类的实例。
Runnable
是一个函数式接口,用于将可运行的代码片段作为参数传递给方法。通常,对于函数式接口,你总是会使用第二种情况。
英文:
For C c = new C()
, the type of the variable is of type C
, whereas with Runnable c = new C()
, the type of the variable is Runnable
. For the first case, only instances of type C
can be stored in the variable. For the second case, instances of a class that implements Runnable
are allowed.
Runnable
is a functional interface that is used to pass pieces of runnable code as parameters to methods. Usually, you're always going to use the second case for functional interfaces.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论