创建一个对象时使用超类引用和使用子类引用有什么区别?

huangapple go评论48阅读模式
英文:

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&lt;5;i++) {
			System.out.println(&quot;Thread2&quot;);
			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.

huangapple
  • 本文由 发表于 2020年8月2日 08:40:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63211325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定