Govt. Exams
Entrance Exams
Option A provides proper generic type safety without unnecessary constraints. While Option C adds a Serializable bound (sometimes desirable), Option A is the most flexible and commonly used pattern for generic response wrappers.
'? extends TargetClass' creates a covariant wildcard allowing lists of TargetClass or any subclass. This is ideal for reading operations when you need polymorphic list handling.
Using 'T extends Number' establishes an upper bound, allowing the method to work with any Number subclass (Integer, Double, Float, etc.) while providing type safety and access to Number methods.
java
List list = new ArrayList();
Class c = list.getClass();
Due to type erasure, getClass() returns ArrayList without generic parameters. Generic information exists only at compile time.
Implementing generic interfaces requires specifying the type parameter. 'implements Comparable<MyClass>' is the proper way to implement.
PECS (Producer Extends, Consumer Super) is a guideline: use 'extends' for producers (reading) and 'super' for consumers (writing).
Covariance means if Dog is a subtype of Animal, then Producer<Dog> is a subtype of Producer<Animal>. Achieved using upper-bounded wildcards.
Producer (Get-Only pattern) uses upper-bounded wildcard (? extends T). It's used when you want to read/produce elements of specific types.
java
List
With upper-bounded wildcard (? extends Number), you can read but cannot add elements (except null) because the compiler doesn't know the exact type.
java
List list = new ArrayList();
Will this compile?
Generics are invariant. ArrayList<Integer> cannot be assigned to List<Number> even though Integer is a subtype of Number. This prevents type safety issues.