为什么下面的代码有效?
interface I { }
class A implements I{
public String toString(){ return "in a"; }
}
class B extends A{
public String toString(){ return "in b"; }
}
B b = new B();
A a = b;
I i = a;
System.out.println(i);
System.out.println((B)a);
System.out.println(b);
如您所见,i
是 println
方法的有效参数。为什么?通过查看此方法接受的参数类型,似乎只有对象是相关的。
我正在寻找答案并找到了一些相关的东西 here : "引用类型都继承自 java.lang.Object。类、枚举、数组和接口(interface)都是引用类型。"
但也发现了这个:“Do interfaces inherit from Object class in Java?”答案是:不,他们没有。就此而言,也没有所有接口(interface)隐式继承的公共(public)“根”接口(interface)(如类的情况)。(*)
这是什么意思?有人能解释一下为什么接口(interface)被接受为 println
函数的参数吗?
我想这里的重点是你不能在没有对象本身的情况下通过接口(interface)传递对象。
但问题仍然存在。为什么编译器接受接口(interface)作为此方法的参数?
最佳答案
The JLS解释一下:
Given a non-generic type declaration C, the direct supertypes of the type C are all of the following:
The direct superclass of C (§8.1.4).
The direct superinterfaces of C (§8.1.5).
The type Object, if C is an interface type with no direct superinterfaces (§9.1.3).
您可能会问为什么 Object 是任何接口(interface)的父类(super class)型。原因是对象不可能不是具体类的实例,而这个具体类不可能不扩展Object。因此,编译器知道对接口(interface)类型的引用是对对象的引用。
https://stackoverflow.com/questions/30152100/