I’m ran into an interesting issue today. Consider the following code
public static class Parent {}
public static class Child extends Parent {}
Set<Child> childs = new HashSet();
Set<Parent> parents = (Set<Parent>)childs; //Error: inconvertible types
Parent parent = (Parent)new Child(); //works?!
Why wouldn’t a cast like that work? I would expect that an implicit cast wouldn’t work due to the various rules of generics, but why can’t an explicit cast work?
The cast doesn’t work because Java generics are not covariant.
If the compiler allowed this:
then what would happen in this case?
The last line would attempt to assign
Parentto aChild— but aParentis not aChild!All
ChildareParent(sinceChild extends Parent) but allParentare notChild.