1

根据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) +"" );
}

}

4

3 回答 3

1
    mystery prob1 = new mystery();
    mysterySubclass prob2 = new mysterySubclass();

在这里,您正在创建两个新对象,因此它们将拥有自己的列表,并且不会像您期望的那样共享一个。

您正在寻找的是:

    mystery prob1 = new mysterySubclass();
    mysterySubclass prob2 = (mysterySubclass)prob1;

试试这个..

于 2012-11-30T05:07:42.273 回答
0

那是因为您调用prob2.addToArray2();它会将"bar"String 添加到变量中的aList属性。prob2考虑到它们共享相同的属性,而不是相同的引用对象引用,所以每个prob都有prob2自己的aList属性值。使用调试器可以轻松证明此行为。

于 2012-11-30T04:49:44.917 回答
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 有 aList 你的 prob2 有 aList 是的,它们是不同的。

第 4 行之后 => prob1.aList -- foo

第 6 行之后 => prob2.aList -- bar

所以 prob2.printArray() 只有“bar”要打印,而且 prob2.printArray2() 基本上它们做同样的事情。

于 2012-11-30T05:20:26.870 回答