为什么数组是对象,却不能作为基类使用? [英] Why are arrays Objects, but can not be used as a base class?

查看:37
本文介绍了为什么数组是对象,却不能作为基类使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 语言规范指定

<块引用>

在 Java 编程语言中,数组是对象(第 4.3.1 节),是动态创建的,并且可以分配给对象类型的变量(第 4.3.2 节).Object 类的所有方法都可以在数组上调用.

所以,考虑到数组是对象——为什么 Java 设计者决定不允许继承和覆盖它,例如,toString()equals()?

当前的语法不允许使用数组作为基类创建匿名类,但我不认为是他们做出决定的原因.

解决方案

Java 是非对象语言和当时一切都是对象的非常慢的语言之间的妥协(想想 Smalltalk).

即使在较新的语言中,在语言级别为数组(通常是映射)拥有一个快速结构被认为是一个战略目标.大多数人不喜欢数组的可继承对象的重量,当然在 JVM 像 JIT 一样进步之前没有人想要这个.

这就是为什么数组虽然是对象,但没有被设计为类实例 ("一个对象是一个类实例或一个数组").能够覆盖数组上的方法几乎没有什么好处,当然也不足以抵消检查应用正确方法的需要(在我看来,还不足以抵消代码阅读难度增加,类似于覆盖运算符时发生的情况).

The Java language specification specifies that

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). All methods of class Object may be invoked on an array.

So, considering arrays are objects — why did the Java designers make the decision not to allow inherit and override from it, for example, toString() or equals()?

The current syntax wouldn't allow creating anonymous classes with an array as the base class, but I don't think that was the reason for their decision.

解决方案

Java was a compromise between non-object languages and very slow languages of that time where everything was an object (think about Smalltalk).

Even in more recent languages, having a fast structure at the language level for arrays (and usually maps) is considered a strategic goal. Most people wouldn't like the weight of an inheritable object for arrays, and certainly nobody wanted this before JVM advances like JIT.

That's why arrays, while being objects, weren't designed as class instances ("An object is a class instance or an array"). There would be little benefit in having the ability to override a method on an array, and certainly not a great-enough one to counterbalance the need to check for the right method to apply (and in my opinion not a great-one enough to counterbalance the increased difficulty in code reading, similar to what happens when you override operators).

这篇关于为什么数组是对象,却不能作为基类使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆