亚型多态性与阵列 [英] Subtype polymorphism and arrays
问题描述
Computer[] labComputers = new Computer[10];
与
public class Computer {
...
void toString(){
// print computer specs
}
}
public class Notebook extends Computer{
...
void toString(){
// print computer specs + laptop color
}
}
每个标变量 labComputers [I]
可以引用电脑
对象或笔记本电脑
对象,因为笔记本电脑
是电脑
的子类。方法调用 labComputers [I]的ToString()
,多态性确保正确的的toString
方法被调用。
each subscripted variable labComputers[i]
can reference either a Computer
object or a Notebook
object because Notebook
is a subclass of Computer
. For the method call labComputers[i].toString()
, polymorphism ensures that the correct toString
method is called.
我不知道如果我们做
Notebook[] labComputers = new Notebook[10];
我会得到什么样的或错误的,如果我与电脑
对象和笔记本电脑
对象
推荐答案
由于这个问题专门询问类型的错误
我会跟下面的场景解释它们
Since the question specifically asks about kind of error
I will explain them with below scenarios
如果您做以下
Notebook[] labComputers = new Notebook[10];
在阵列现在可以只设置笔记本对象。
Now you can only set Notebook objects in array.
labComputers[0] = new Notebook(); // Fine
labComputers[1] = new Computer(); // Compilation error
现在,如果你做
Computer[] notebooks = new Notebook[10];
notebooks[0] = new Notebook();
notebooks[1] = new Computer(); // <--- ArrayStoreException
由于数组是 covarant
,自然界中的具体化,即
。如果子
是一个亚型中超
,然后数组类型子[]
是的亚型超级[]
和数组强制在运行时它们的元素类型会引起ArrayStoreException信息
Because arrays are covarant
,reified
in nature ie. if Sub
is a subtype of Super
, then the array type Sub[]
is a subtype of Super[]
, and arrays enforce their element types at run time it will cause ArrayStoreException
您可以阅读甲骨文的文档有关多态性知道更多的它是如何工作。
You can read oracle docs about Polymorphism to know more how it works.
这篇关于亚型多态性与阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!