According to the javadocs “A subclass inherits all the members (fields, methods, and nested classes) from its superclass“. Also, Java manipulates objects by reference So why does this subclass return the wrong value for aList[0] ? It seems each class is modifying their own array when I expect them to both modify the same array.
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) +"" );
}
}
Here you are creating two new objects, so they will have their own list and wont share one as you expect.
What you are looking for is:
Try this..