java - Is `Box<Cat>` subtype of `Box<? extends Animal>`? -
java code:
class animal {} class cat extends animal {} class box<t> {} public class test { public void hello(box<? extends animal> box) {} } box<animal> box1 = new box<animal>(); box<cat> box2 = new box<cat>(); new test().hello(box1); new test().hello(box2); from liskov substitution principle, since box2 type box<cat> can used requires type box<? extends animal>, can say:
box<cat> subtype of box<? extends animal>
actually: i'm not sure if box<? extends animal> , ? extends animal types
the java language specification states
given generic type declaration c<f1,...,fn> (n > 0), direct supertypes of parameterized type c<t1,...,tn>, ti (1 ≤ ≤ n) type, of following:
c<s1,...,sn>, sicontains ti (1 ≤ ≤ n) (§4.5.1). and about containing described above
a type argument t1 said contain type argument t2, written t2 <= t1, if set of types denoted t2 provably subset of set of types denoted t1 under the reflexive , transitive closure of next rules (where <: denotes subtyping (§4.10)):
? extends t <= ? extends s if t <: s ? extends t <= ? t <= t t <= ? extends t [...] // see these if interested in case,
box<cat> we care cat. above, can ? extends cat contains cat. can ? extends animal contains ? extends cat, since cat <: animal. ? extends animal contains cat. hence box<? extends animal> direct supertype of parameterized type box<cat>
therefore, box<cat> subtype of box<? extends animal>.
java generics type-systems
No comments:
Post a Comment