java - 接口(interface)是否被视为对象?

为什么下面的代码有效?

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);

如您所见,iprintln 方法的有效参数。为什么?通过查看此方法接受的参数类型,似乎只有对象是相关的。

我正在寻找答案并找到了一些相关的东西 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/

相关文章:

google-api - YouTube API 直播

java - 有没有办法清除JAVA中对象的所有字段?

php - 第 2 行超出范围 (2 - 1) laravel-excel

git - 我如何将 openshift git 存储库连接到 bitbucket

r - 加载 Data.Table 后遮盖的润滑对象

unity3d - 团结 |查找具有指定父对象的子游戏对象

spring-mongo - Spring Mongo 从 json 字符串转换为文档

python - 在python中将多个png组合成一个pdf

ruby-on-rails - 使用 Rails 将带连字符的单词的两个部分都大写

opengl-es - 使用具有多个颜色纹理附件的 FrameBufferObject