You've already seen that polymorphism applies to the "base" type of the collection:
List
In other words, we were able to assign an ArrayList to a List reference, because List is a supertype of ArrayList. Nothing special there—this polymorphic assignment works the way it always works in Java, regardless of the generic typing.
But what about this?
class Parent { }
class Child extends Parent { }
List
Think about it for a minute.
Keep thinking…
No, it doesn't work. There's a very simple rule here—the type of the variable declaration must match the type you pass to the actual object type. If you declare List
These are wrong:
List< Object > myList = new ArrayList
List
// remember that Integer is a subtype of Number
But these are fine:
List
List
No comments:
Post a Comment