根据javadocs“子类继承其超类的所有成员(字段、方法和嵌套类) ”。此外,Java 通过引用来操作对象 那么为什么这个子类会为 aList[0] 返回错误的值呢?当我希望它们都修改同一个数组时,似乎每个类都在修改自己的数组。
public class mystery {
protected List<String> aList;
public mystery() {
aList = new ArrayList<String>();
}
public void addToArray() {
//"foo" is successfully added to the arraylist
aList.add("foo");
}
public void printArray() {
System.out.println( "printArray " + aList.get(0) +"" );
}
public static void main(String[] args) {
mystery prob1 = new mystery();
mysterySubclass prob2 = new mysterySubclass();
//add "foo" to array
prob1.addToArray();
//add "bar" to array
prob2.addToArray2();
//expect to print "foo", works as expected
prob1.printArray();
//expect to print "foo", but actually prints "bar"
prob2.printArray();
//expect to print "foo", but actually prints "bar"
prob2.printArray2();
}
}
public class mysterySubclass extends mystery {
public void mysterySubclass() {}
public void addToArray2() {
aList.add("bar");
}
public void printArray2() {
System.out.println( "printArray2 " + super.aList.get(0) +"" );
}
}