1Z0-809 · Question #224
You have been asked to define the ProductCode class. The definition of the ProductCode class must allow c1 instantiation to succeed and cause a compilation error on c2 instantiation. Which…
The correct answer is B. class ProductCode<T, S extends T> { T c1; S c2; }. Option B works because S extends T enforces a compile-time constraint that S must be a subtype of T. So an instantiation like ProductCode<Animal, Dog> (where Dog extends Animal) succeeds as c1, while ProductCode<Dog, Animal> fails as c2 because Animal is not a subtype of Dog…
Question
Options
- Aclass ProductCode<T, S<Integer>> { T c1; S c2; }
- Bclass ProductCode<T, S extends T> { T c1; S c2; }
- Cclass ProductCode<T, S> { T c1; S c2; }
- Dclass ProductCode<T, S super T> { T c1; S c2; }
How the community answered
(51 responses)- A6% (3)
- B78% (40)
- C12% (6)
- D4% (2)
Explanation
Option B works because S extends T enforces a compile-time constraint that S must be a subtype of T. So an instantiation like ProductCode<Animal, Dog> (where Dog extends Animal) succeeds as c1, while ProductCode<Dog, Animal> fails as c2 because Animal is not a subtype of Dog.
Why the distractors are wrong:
- A -
S<Integer>is not legal Java generic syntax for a type parameter declaration; you cannot parameterize a type variable with a concrete type like this. - C - No bounds means any types are accepted, so both
c1andc2instantiations would compile, failing the requirement forc2to error. - D -
S super Tis not valid in a class type parameter declaration; lower-bounded wildcards (? super T) are only legal in use-site wildcard contexts (e.g., method parameters), not in class headers.
Memory tip: Think of extends in a type parameter (S extends T) as "S must fit inside T's hierarchy going down." If you flip the types in the instantiation so the relationship breaks, the compiler catches it - that's exactly the mechanism that makes c2 fail.
Community Discussion
No community discussion yet for this question.