So I have two classes. Class B extends class A. I’m creating an ArrayList containing objects of type B, so the list is of type ArrayList<B>. I want to use that ArrayList in a method useList that has an input parameter type of ArrayList<A>. It stands to reason that since B is a child class of A, it can be used everywhere that A is, including in this application.
HOWEVER, the compiler doesn’t seem to like this (see error messages in code below). I also tried casting my ArrayList<B> to ArrayList<A> when passing it into the method, but that one didn’t work either.
Code:
public class Test {
private class A { }
private class B extends A { }
public static void useList(ArrayList<A> aList) { }
public static void main(String[] args) {
ArrayList<B> bList = new ArrayList<B>();
/* "The method test(ArrayList<Test.A>) in the type Test
* is not applicable for the arguments (ArrayList<Test.B>)" */
useList(bList);
/* "Cannot cast from ArrayList<Test.B> to ArrayList<Test.A>" */
useList((ArrayList<A>)bList);
}
}
I’m undoubtedly doing something silly, so any advice would be appreciated!
Thanks!
just declare
useListto expect a parameter of typeArrayListwith elements that extendA: