继承之后的使用注意事项_ArrayStoreException

今天在看Core In Java第五章节时,看到一个很感兴趣的知识点,如下:

在Java中,子类数组的引用可以转换成超类数组的引用,而不需要采用强制转换。但是,在超类数组的引用添加超类类型引用对象之后,就会出错(ArrayStoreException)!代码如下:


/**
* 在第五章节继承中提到了一个很重要的概念
*
* 确切的讲是一个继承使用时的忌讳
*
* 使用子类类型定义一个数组,然后让一个父类类型数组引用,在父类数组中添加父类类型对象,将出错
*
* ArrayStoreException
*
* @author Administrator
*
*/
public class ArrayStoreExceptionTest {

/**
* 测试在继承中的注意事项及忌讳
*
* @param args
*/
public static void main(String[] args) {
Student[] students = new Student[10];
Person[] persons = students;
// 内部类的实例化过程
Person p1 = new ArrayStoreExceptionTest().new Person(1001, "Jessica");
persons[0] = p1;
students[0].setScore(200.1);
}

/**
* Super class Person
*
* @author Administrator
*
*/
class Person {
private int id;

private String name;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Person(int id, String name) {
super();
this.id = id;
this.name = name;
}

public Person() {
super();
}

}

/**
* Subclass Student
*
* @author Administrator
*
*/
class Student extends Person {
private double score;

public Student(int id, String name, double score) {
super(id, name);
this.score = score;
}

public double getScore() {
return score;
}

public void setScore(double score) {
this.score = score;
}
}
}



以上代码中,在main()方法中的代码可以正常编译通过,在运行时将抛出一个ArrayStoreException的运行时异常,原因是:由于persons超类数组对象的引用指向了students子类数组对象的引用,当为persons[0]添加父类对象引用时,将出现这样的情况:JVM会进行检查,由于引用的是子类数组类型对象引用,添加父类引用类型对象如果可以通过,在以下语句将出现更严重的异常!

students[0].setScore(200.1);
//将会访问一个不存在的实例域,进而搅乱相邻存储空间的内容!


所以,以上代码块执行之后,将抛出ArrayStoreException,这是一个运行时异常的子类异常!这是使用继承之后的一种忌讳!一定要注意避免!


Exception in thread "main" java.lang.ArrayStoreException:

com.harry.coreInJava.chap5.ArrayStoreExceptionTest$Person

at com.harry.coreInJava.chap5.ArrayStoreExceptionTest.main

(ArrayStoreExceptionTest.java:30)



所以,如果定义的是一个数组类型对象,则有必要记住这个对象中可以添加什么类型的对象,而不是因为继承关系而扰乱了我们的判断力!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值