亚型多态性与阵列 [英] Subtype polymorphism and arrays

查看:126
本文介绍了亚型多态性与阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

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