Today I ran into an interesting problem. 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 not make such a throw? I would expect that an implicit cast will not work due to different generic rules, but why doesn't explicit cast work?
The cast does not work because Java Generators are not covariant .
If the compiler allowed this:
List<Child> children = new ArrayList(); List<Parent> parents = (List<Parent>)children;
what will happen in this case?
parents.add(new Parent()); Child c = children.get(0);
The last line will try to appropriate Parent Child- but Parent not Child!
Parent
Child
All Childare Parent(since Child extends Parent), but all are Parentnot Child.
Child extends Parent
A Set<Parent> Parent. A Set<Child> Child. , Parent, Child, , , .
Set<Parent>
Set<Child>
(sic) . () , .
, -:
Set<Child> childs = new HashSet(); Set<? extends Parent> parents = childs;
Set - Set
, , , . , , . , , , , , , , , , , . - , : (, ) (/).
:
Parent parent = new Child();
Stéphane
не нарушают стиль? - jquery