See title. I can't figure out why it doesn't work.
Example of non-working code:
displayList(subclassArrayList);
...gives me
"incompatible types: ArrayList<B> cannot be converted to ArrayList<A>"
My classes:
public static class A{
int someAttribute = 0;
A(){}
}
public static class B extends A{
int someOtherAttribute = 2;
B(int value){
this.someOtherAttribute = value;
}
}
Somewhere in main:
ArrayList<B> subclassArrayList = new ArrayList();
subclassArrayList.add(new B(3));
subclassArrayList.add(new B(5));
subclassArrayList.add(new B(7));
The offending function:
void displayList(ArrayList<A> superclassList){
for(A item : superclassList){
System.out.print(item.someOtherAttribute);
System.out.print(" ");
}
}
However, I've found that I'm able to do this with no apparent problems.
ArrayList<A> superclassArrayList = new ArrayList();
superclassArrayList.addAll(subclassArrayList);
displayList(superclassArrayList);
What exactly is my code doing behind the scenes, here?