Say you have:
public interface A {}
public class B implements A {}
public class C {
void foo (List<A>) {}
}
public class Test {
List<A> x = new List<A>();
List<A> x = new List<B>();
B b = new B();
x.add(b);
new C().foo(x);
}
Now it’s obvious that declaring is the right way to do this, and you get a compilation error for declaration two. I would like to know exactly why Java chooses to ensure type safety this way; if the list of cats is still a list of animals, why the method that expects the list of animals to stop receiving a bunch of cats?
Curiosity, more than anything, and a chance to improve my knowledge.
Cheers, Dave.
source
share