根据javadocs“子类继承所有成员(字段,方法和嵌套类)from its superclass”。另外,Java manipulates objects by 引用为什么这个子类为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) +"" );
}
}
答案 0 :(得分:1)
mystery prob1 = new mystery();
mysterySubclass prob2 = new mysterySubclass();
您正在创建两个新对象,因此他们将拥有自己的列表,并且不会按预期分享一个。
您正在寻找的是:
mystery prob1 = new mysterySubclass();
mysterySubclass prob2 = (mysterySubclass)prob1;
试试这个..
答案 1 :(得分:0)
这是因为您正在调用prob2.addToArray2();
,这会将"bar"
字符串添加到aList
变量中的prob2
属性中。考虑到它们共享相同的属性,而不是对象引用的相同引用,因此每个prob
和prob2
都有自己的aList
属性值。使用调试器可以很容易地证明这种行为。
答案 2 :(得分:0)
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();
你的prob1有一个列表 你的prob2有一个列表 是的,他们是不同的。
在第4行=&gt;之后prob1.aList - foo
第6行后的=&gt; prob2.aList - bar
所以prob2.printArray()只有“bar”来打印,还有prob2.printArray2() 基本上他们做同样的事情。