2

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 with type Box<Cat> can be used where it requires a type Box<? extends Animal>, can I say:

Box<Cat> is subtype of Box<? extends Animal>

Actually: I'm not even sure if Box<? extends Animal> and ? extends Animal are types

David Conrad
  • 15,432
  • 2
  • 42
  • 54
Freewind
  • 193,756
  • 157
  • 432
  • 708
  • a `Box extends Animal>` may well be a `Box` - and a `Box` is not a subtype of a `Box`... see also: http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitly-p – assylias Jun 24 '14 at 22:16
  • Also see http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ207 - it explains this issue very well – Marco13 Jun 24 '14 at 23:31

1 Answers1

5

The Java Language Specification states

Given a generic type declaration C<F1,...,Fn> (n > 0), the direct supertypes of the parameterized type C<T1,...,Tn>, where Ti (1 ≤ i ≤ n) is a type, are all of the following:

  • [...]
  • C<S1,...,Sn>, where Sicontains Ti (1 ≤ i ≤ n) (§4.5.1).

and about containing described above

A type argument T1 is said to contain another type argument T2, written T2 <= T1, if the set of types denoted by T2 is provably a subset of the set of types denoted by T1 under the reflexive and transitive closure of the following rules (where <: denotes subtyping (§4.10)):

? extends T <= ? extends S if T <: S

? extends T <= ?

T <= T

T <= ? extends T

[...] // see these if you are interested

In your case,

Box<Cat>

we care about Cat. With the above, we can say that ? extends Cat contains Cat. We can then say ? extends Animal contains ? extends Cat, since Cat <: Animal. So ? extends Animal contains Cat. Therefore Box<? extends Animal> is a direct supertype of the parameterized type Box<Cat>

Therefore, Box<Cat> is a subtype of Box<? extends Animal>.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724