java - 为什么我们可以将数组分配给 Java 中 Object 类型的引用?

标签 java arrays

作为学习的一部分,下面是我试图理解的病理示例,

class C{}; interface I{}; class S extends C implements I{};
class B{};

通过这些声明,我可以说,class C class BObject 类的直接子类,并且可以访问 的所有方法code>Object 这些类中的类。但是,

1) 当我声明 interface I{}; interface IObject 类有什么关系?

接下来,下面是对数组类型的一些赋值,然后是子类到父类(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/

相关文章:

java - 如何使程序将文件从包复制到 java 中的 user.dir?

java - 如何从给定的字符串中删除子字符串?

java - java中UUID转换为int

java - 如何使用使用 SSL 和通配符/自签名证书保护的 Maven 2 存储库?

arrays - 从数组创建对象

java - 堆栈添加机不添加但挂起等待更多参数

java - Java中的ArrayList和输入

java - @Test 后回滚事务

java - 如何为双ArrayList实现Parcelable?

javascript - 使用 javascript (jquery) 使用 HTTP Get 获取 JSON 数组