1. this和super异同
- 相同: 都可以调用构造方法,this调用本类的其他构造方法,super调用父类构造方法
- 不同: this可以调用隐性参数,super可以调用超累方法
- 不同: super不是对象的引用,不能赋值给变量。只是指示编译器调用超类方法的特殊关键字
2. ArrayStoreException
有类Programmer继承自Person:
public class Person {……}
public class Programmer extends Person {
……
private long income;
public long getIncome() {
return income;
}
public void setIncome(long income) {
this.income = income;
}
……
}
又有如下操作:
Programmer[] programmers = new Programmer[10];
Person[] human = programmers;
human[0] = new Person(true, "xxx", "333");
programmers[0].setIncome(10000);
这段代码在编辑器中不会报错,看起来运行到最后一步,会使一个Person实例执行属于子类Programmer的setIncome(long)方法。
实际并不会,编译器在编译到第三行时,就会抛出Exception in thread "main" java.lang.ArrayStoreException: Person。
这说明在JVM中,数组要记录创建时的类型,保证只接受类型兼容的实例。