0

Can someone please explain to me why this would cause a runtime exception? It seems to me like I'm accessing an arraylist of the type variable B exclusively.

class A {}
class B extends A {}
List<B> bL = new ArrayList<B>();
List<A> aL = bL;
aL.add(new A());
B b = bL.get(0); // runtime exception
Chip
  • 5
  • 1
  • 3

1 Answers1

2

You shouldn't have been able to compile your code successfully. You should be getting a compiler error at this line:

List<A> aL = bL;

because a List<Subclass> is not a List<Superclass>. That is disallowed specifically because of what you just attempted - insert a superclass instance into a list of subclass instances.

rgettman
  • 176,041
  • 30
  • 275
  • 357