How many lines fail to compile?
class Shape { } class Rectangle extends Shape { } class Printer<E extends Shape> { public void roll(E e) { } } public class Main { Printer<Rectangle> p1 = new Printer<Rectangle>(); Printer<Shape> p2 = new Printer<Rectangle>(); Printer<? extends Shape> p3 = new Printer<Rectangle>(); Printer<? extends Shape> p4 = new Printer<Shape>(); Printer<? super Shape> p5 = new Printer<Rectangle>(); Printer<? super Shape> p6 = new Printer<Shape>(); }
The Printer class uses a formal type parameter named E with a constraint.
The key to this question is knowing that with generics, the extends keyword means any subclass or the class can be used as the type parameter.
This means both Shape and Rectangle are OK.
The p1 declaration is fine because the same type is used on both sides of the declaration.
The p2 declaration does not compile because generics require the exact same type when not using wildcards.
The p3 and p4 declarations are both fine because this time there is an upper bound to specify that the type can be a subclass.
By contrast, the super keyword means it has to be that class or a superclass.
The p6 declaration is OK, but the p5 one is a problem because it uses a subclass.
Since p2 and p5 don't compile, the answer is Option B.