尝试将数组的元素设置为超类对象时发生ArrayStoreException [英] ArrayStoreException when trying to set an element of an array to a superclass object

查看:79
本文介绍了尝试将数组的元素设置为超类对象时发生ArrayStoreException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A {}
class B extends A {}

您好,我正在学习Java,并且试图了解其工作原理:

Hi, I'm learning Java and I'm trying to understand why this works:

A[] tab = new A[10];
tab[0] = new B();

不是这个:

A[] tab = new B[10];
tab[0] = new A();

此行A[] tab = new B[10];表示编译器正在为内存中的B预订10个位置. tab[0] = new A()tab[0]设置为等于(c)小于B(B extends A)的新A对象.

this line A[] tab = new B[10]; means that the compiler is booking 10 places for B in memory. tab[0] = new A() is setting tab[0] equal to a new A object that is smaller (?) than B (B extends A).

为什么会出现ArrayStoreException: A错误?如何运作?

Why is there an ArrayStoreException: A error ? How does it work ?

推荐答案

您可以在该对象内部存储该对象的子类.即B可以存储在A中,但是A是类型B的超类.基本上,继承链中位于类X之下的任何类都可以称为类型X,但是继承链中位于类X之上的任何类都不能称为类型X.

You can store subclasses of an object, inside that object. ie B can be stored in A, but A is a superclass of type B. Basically, any class below class X in the inheritance chain can be referred to as type X, but any class above class X in the inheritance chain can NOT be referred to as type X.

您的示例

A[] tab = new A[10]; // Perfectly fine. Equal objects.
tab[0] = new B(); // B is a subclass of A, so this is allowed.

A[] tab = new B[10]; // Same principle as above, B is a subclass of A
tab[0] = new A(); // A is a SUPERCLASS of B, so it can not be referred to as A

简而言之,如果XY的子类,则只能将X称为Y. (或子类的子类.这是递归定义).

In short, X can only be referred to as Y, if X is a subclass of Y. (Or a subclass of a subclass. It's a recursive definition).

我们使用一些英语术语

让我们使用ItemBook,而不是AB.

Instead of A and B, let's have Item and Book.

public class Item {}

public class Book extends Item {}

现在,说起来很合理

Item b = new Book(); // All Books are items.

说没有道理

Book b = new Item(); // All items are definitely not books.

这篇关于尝试将数组的元素设置为超类对象时发生ArrayStoreException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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