作为学习的一部分,下面是我试图理解的病理示例,
class C{}; interface I{}; class S extends C implements I{};
class B{};
通过这些声明,我可以说,class C
class B
是 Object
类的直接子类,并且可以访问 的所有方法code>Object
这些类中的类。但是,
1) 当我声明 interface I{};
interface I
与 Object
类有什么关系?
接下来,下面是对数组类型的一些赋值,然后是子类到父类(super class)的赋值,反之亦然。
C[] c = new C[4];
S[] s = new S[6];
I[] i = new S[0];
B[] b = new B[2];
//i = new C[2]; Compile error
i =s; c=s; s = (S[])c; i = (I[])c;
i = (I[])b; //Run-time error
我了解到数组是“一等对象”和 Object
类的直接子类,
Object o = c; // i mean `I i = c;` will not work `I[] i =c;` works
2) 关于上面的定义(语法),“数组是第一类对象”是什么意思?因为 Object[] oa = c;
对我来说有意义 C 类
是Object
类的直接子类。
最佳答案
When i declare interface I{}; How is interface I related to Object class?
来自Java Language Specification :
If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.
How would i consider reference variable o pointing to array c
如评论中所述,array 本身是 Object
的子类,因此以下赋值是有效的:
Object o = c;
相关部分来自Java Language Specification说:
In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2).
这也是“数组是一等对象”的意思。在 Java 中,数组不是特殊类型或某种特殊构造 - 它本质上是 Object
的子类,具有附加字段(特别是 length
)(以及一些附加编译器支持能够在句法上描述和初始化数组)。
关于java - 为什么我们可以将数组分配给 Java 中 Object 类型的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25969871/