Java Generics Inheritance Rules and Wildcards: extends, super and ?
Master Java wildcards: why List<Manager> is not a List<Employee>, how arrays differ, raw-type pitfalls, ? extends for reading, ? super for writing, the PECS rule, Comparable<? super T>, unbounded wildcards and wildcard capture with helper methods.
kvi5hnuCode Sprout team member13 min readOn this page
Generics and inheritance interact in a way that surprises almost everyone at first: a Pair<Manager> is not a Pair<Employee>, even though every manager is an employee. This article explains why that rule is necessary, and then introduces wildcard types, Java's safe "escape hatch" that brings back the flexibility. Wildcards are what make signatures like Collections.max and List.addAll both safe and convenient. Once you understand them, those intimidating declarations in the API documentation become readable.
Inheritance rules for generic types
Take a class and a subclass, Employee and Manager. Is Pair<Manager> a subtype of Pair<Employee>? Perhaps surprisingly, no. This doesn't compile:
Manager[] topHonchos = . . .;
Pair<Employee> result = ArrayAlg.minmax(topHonchos); // ERROR: minmax returns Pair<Manager>
In general, there is no relationship between Pair<S> and Pair<T>, however S and T are related.
That seems harsh, but it's necessary for type safety. Suppose the conversion were allowed:
var managerBuddies = new Pair<Manager>(ceo, cfo);
Pair<Employee> employeeBuddies = managerBuddies; // illegal, but suppose it wasn't
employeeBuddies.setFirst(lowlyEmployee);
The last line is clearly legal: you can put an Employee into a Pair<Employee>. But employeeBuddies and managerBuddies refer to the same object. We'd have paired the CFO with a lowly employee, which must never happen in a Pair<Manager>. Code reading managerBuddies.getFirst() would get an Employee where it expects a Manager.
Arrays are different
Here generic types differ from arrays. You can assign a Manager[] to an Employee[] variable:
Manager[] managerBuddies = { ceo, cfo };
Employee[] employeeBuddies = managerBuddies; // OK
Arrays are covariant, but they come with special run-time protection. Every array knows its element type, so storing a plain employee in employeeBuddies[0] makes the virtual machine throw an ArrayStoreException. Generic objects can't do this, because erasure means a Pair doesn't know its type argument at run time. So the check has to happen at compile time, and the only safe rule is "no relationship".
Raw types defeat the checks
You can always convert a parameterized type to its raw type. Pair<Employee> is a subtype of the raw Pair. That's needed to interact with legacy code, but it opens a hole:
var managerBuddies = new Pair<Manager>(ceo, cfo);
Pair rawBuddies = managerBuddies; // OK
rawBuddies.setFirst(new File(". . .")); // only an unchecked warning
That sounds scary, but you're no worse off than before generics existed. The VM's integrity isn't at risk: when the foreign object is later read with getFirst and assigned to a Manager variable, a ClassCastException is thrown, just as in the old days. You only lose the extra safety that generics normally provide. This is one more reason to avoid raw types in new code.
Generic classes can extend generic classes
Generic classes can extend or implement other generic classes, just like ordinary classes. For example, ArrayList<T> implements List<T>, so an ArrayList<Manager> converts to a List<Manager>. But, as you just saw, an ArrayList<Manager> is not an ArrayList<Employee> or a List<Employee>.

Wildcard types
Type-system researchers had known for some time that a rigid generic type system is unpleasant to use. Java's designers added an ingenious, and still type-safe, escape hatch: the wildcard type.
The wildcard concept: ? extends
In a wildcard type, the type argument is allowed to vary. The type
Pair<? extends Employee>
denotes any Pair whose type argument is a subtype of Employee, such as Pair<Manager>, but not Pair<String>.
Suppose you want a method that prints a pair of employees:
public static void printBuddies(Pair<Employee> p) {
Employee first = p.getFirst();
Employee second = p.getSecond();
System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
}
You can't pass a Pair<Manager> to it, which is rather limiting. The fix is simple. Use a wildcard:
public static void printBuddies(Pair<? extends Employee> p)
Pair<Manager> is a subtype of Pair<? extends Employee>, so the call works.
Can the wildcard be used to corrupt a Pair<Manager>?
var managerBuddies = new Pair<Manager>(ceo, cfo);
Pair<? extends Employee> wildcardBuddies = managerBuddies; // OK
wildcardBuddies.setFirst(lowlyEmployee); // compile-time error
No. Look at what the compiler knows about the methods of Pair<? extends Employee>. In pseudo-code:
? extends Employee getFirst()
void setFirst(? extends Employee)
setFirst can't be called. Its parameter has some specific type that extends Employee. Is it Employee? Manager? Some other subclass? The compiler has no way to know, so it can't accept lowlyEmployee. For the same reason, it rejects even a Manager argument. The only value it accepts is null.
getFirst still works. It returns some specific subtype of Employee. The compiler doesn't know which, but it can guarantee that assigning the result to an Employee variable is safe.
That is the key idea of bounded wildcards: they separate the safe accessor methods from the unsafe mutator methods.
Supertype bounds: ? super
Wildcard bounds are like type variable bounds, with one extra ability: you can give a supertype bound:
? super Manager
This wildcard stands for any supertype of Manager. (It's a stroke of luck that the existing super keyword describes the relationship so well.)
Why would you want that? A supertype bound gives the opposite behavior: you can pass arguments to methods, but you can't use return values. Pair<? super Manager> has, in pseudo-code:
void setFirst(? super Manager)
? super Manager getFirst()
The parameter type of setFirst is some specific type T such that Manager is a subtype of T: here Object, Employee or Manager (more if they implemented interfaces). The compiler doesn't know which, so it can't accept an Employee or an Object, since T might be Manager. You can only pass a Manager, or a subtype such as Executive. Conversely, getFirst gives no guarantee about the returned type. You can only assign it to Object.
A typical example: given an array of managers, put the ones with the lowest and highest bonus into a Pair. What kind of pair? Pair<Manager> is the obvious choice, but a Pair<Employee>, or even a Pair<Object>, should be acceptable too. This method accepts any suitable pair:
public static void minmaxBonus(Manager[] a, Pair<? super Manager> result) {
if (a.length == 0) return;
Manager min = a[0];
Manager max = a[0];
for (int i = 1; i < a.length; i++) {
if (min.getBonus() > a[i].getBonus()) min = a[i];
if (max.getBonus() < a[i].getBonus()) max = a[i];
}
result.setFirst(min);
result.setSecond(max);
}
Intuitively: wildcards with supertype bounds let you write to a generic object, and wildcards with subtype bounds let you read from it.

Comparable<? super T>
Here's another use of supertype bounds. Comparable is generic:
public interface Comparable<T> {
public int compareTo(T other);
}
The type variable gives the type of other. String implements Comparable<String>, so its method is int compareTo(String other), with the right parameter type and no cast, as there used to be when the parameter was Object.
So should a generic min method be declared as follows?
public static <T extends Comparable<T>> T min(T[] a)
That's more thorough than the raw T extends Comparable, and it works for many classes. For a String array, T is String, which is a subtype of Comparable<String>. But it fails for LocalDate. LocalDate implements ChronoLocalDate, which extends Comparable<ChronoLocalDate>. So LocalDate implements Comparable<ChronoLocalDate>, not Comparable<LocalDate>.
Supertypes to the rescue:
public static <T extends Comparable<? super T>> T min(T[] a)
Now compareTo has the form int compareTo(? super T). It may take a T, or, as with LocalDate, a supertype of T. Either way, passing a T to it is safe.
To the uninitiated, <T extends Comparable<? super T>> looks intimidating. That's unfortunate, because its purpose is to help application programmers by removing unnecessary restrictions on what they can pass. Application programmers can learn to skim such declarations and trust the library authors. If you're a library author, get comfortable with wildcards, or your users will curse you and sprinkle random casts around until their code compiles.
Unbounded wildcards
You can even use a wildcard with no bound: Pair<?>. At first glance it looks like the raw type Pair, but it's very different. Pair<?> has methods like
? getFirst()
void setFirst(?)
The result of getFirst can only be assigned to an Object, and setFirst can never be called, not even with an Object. Only setFirst(null) works. That's the essential difference: with the raw type Pair, you can call setFirst with any object and corrupt the pair. Pair<?> stays type-safe.
Why would you want such a feeble type? It's perfect for simple operations that don't care about the type argument. This method tests whether a pair contains a null:
public static boolean hasNulls(Pair<?> p) {
return p.getFirst() == null || p.getSecond() == null;
}
You could avoid the wildcard by making hasNulls generic, public static <T> boolean hasNulls(Pair<T> p), but the wildcard version is easier to read.
Wildcard capture
Let's write a method that swaps the elements of a pair:
public static void swap(Pair<?> p)
A wildcard isn't a type variable, so you can't use ? as a type. This is illegal:
? t = p.getFirst(); // ERROR
p.setFirst(p.getSecond());
p.setSecond(t);
That's a problem, because we need to hold the first element temporarily. The solution is a generic helper method:
public static <T> void swapHelper(Pair<T> p) {
T t = p.getFirst();
p.setFirst(p.getSecond());
p.setSecond(t);
}
swapHelper is generic, while swap has the fixed parameter type Pair<?>. Now swap can call the helper:
public static void swap(Pair<?> p) { swapHelper(p); }
Here the type parameter T of swapHelper captures the wildcard. Nobody knows which type the wildcard stands for, but it is one definite type, and swapHelper makes perfect sense with T as that type.
Of course, we could have just written <T> void swap(Pair<T> p) directly. But sometimes a wildcard type arises naturally in the middle of a computation:
public static void maxminBonus(Manager[] a, Pair<? super Manager> result) {
minmaxBonus(a, result);
PairAlg.swapHelper(result); // OK: swapHelper captures the wildcard type
}
Here, wildcard capture can't be avoided.
Capture is only allowed in limited circumstances: the compiler must be able to guarantee that the wildcard stands for one definite type. For example, the T in ArrayList<Pair<T>> can never capture the wildcard in ArrayList<Pair<?>>, because the list might hold two pairs whose ? stand for different types.
A complete example
The program gathers the techniques of this article: invariance, array covariance with ArrayStoreException, raw-type corruption, ? extends and ? super methods, removeIf with a Predicate<Object>, Comparable<? super T> with dates, PECS in Collections.copy, and wildcard capture.
import java.time.*;
import java.util.*;
import java.util.function.*;
public class Solution {
public static void main(String[] args) {
var ceo = new Manager("Grace Ho", 180_000);
var cfo = new Manager("Omar Diaz", 150_000);
var dev = new Employee("Lena Park", 95_000);
var managerBuddies = new Pair<Manager>(ceo, cfo);
// 1. Pair<Manager> is NOT a Pair<Employee>
// Pair<Employee> employeeBuddies = managerBuddies; // compile-time error
// arrays are covariant, but guarded at run time
Manager[] managerArray = { ceo, cfo };
Employee[] employeeArray = managerArray; // compiles
try {
employeeArray[0] = dev;
} catch (ArrayStoreException e) {
System.out.println("ArrayStoreException: " + e.getMessage());
}
// raw types let you defeat the checks; the failure surfaces later
corruptThroughRawType(managerBuddies);
try {
Manager first = managerBuddies.getFirst();
System.out.println(first);
} catch (ClassCastException e) {
System.out.println("ClassCastException when reading the corrupted pair");
}
managerBuddies.setFirst(ceo);
// 2. ? extends: read as Employee, can't write
printBuddies(managerBuddies);
printBuddies(new Pair<Employee>(dev, ceo));
// 3. ? super: write Managers, read only as Object
ceo.setBonus(1_000_000);
cfo.setBonus(500_000);
Manager[] managers = { ceo, cfo };
var result = new Pair<Employee>();
minmaxBonus(managers, result);
System.out.println("first: " + result.getFirst().getName() + ", second: " + result.getSecond().getName());
maxminBonus(managers, result);
System.out.println("first: " + result.getFirst().getName() + ", second: " + result.getSecond().getName());
var anything = new Pair<Object>();
minmaxBonus(managers, anything);
System.out.println("into a Pair<Object>: " + anything.getFirst());
// a Predicate<Object> works where Predicate<? super Employee> is expected
var staff = new ArrayList<Employee>(List.of(ceo, cfo, dev));
Predicate<Object> isManager = obj -> obj instanceof Manager;
staff.removeIf(isManager);
System.out.println("after removeIf: " + staff);
// Comparable<? super T> lets LocalDate in
var dates = new LocalDate[] { LocalDate.of(2025, 3, 1), LocalDate.of(2024, 7, 4) };
LocalDate earliest = min(dates);
System.out.println("earliest: " + earliest);
// PECS in the library: copy(List<? super T> dest, List<? extends T> src)
List<Object> dest = new ArrayList<>(Arrays.asList("x", "y"));
List<Integer> src = List.of(7, 8);
Collections.copy(dest, src);
System.out.println("copied: " + dest);
// 4. unbounded wildcard and wildcard capture
System.out.println("hasNulls: " + PairAlg.hasNulls(new Pair<String>("a", null)));
Pair<?> unknown = new Pair<>("left", "right");
PairAlg.swap(unknown);
System.out.println("swapped: " + unknown.getFirst() + ", " + unknown.getSecond());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
static void corruptThroughRawType(Pair<Manager> p) {
Pair raw = p; // OK: every parameterized type converts to its raw type
raw.setFirst("not a manager"); // only an unchecked warning
}
public static void printBuddies(Pair<? extends Employee> p) {
Employee first = p.getFirst();
Employee second = p.getSecond();
System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
// p.setFirst(first); // compile-time error: can't pass anything but null
}
public static void minmaxBonus(Manager[] a, Pair<? super Manager> result) {
if (a.length == 0) return;
Manager min = a[0];
Manager max = a[0];
for (int i = 1; i < a.length; i++) {
if (min.getBonus() > a[i].getBonus()) min = a[i];
if (max.getBonus() < a[i].getBonus()) max = a[i];
}
result.setFirst(min);
result.setSecond(max);
// Manager m = result.getFirst(); // compile-time error: only Object is known
}
public static void maxminBonus(Manager[] a, Pair<? super Manager> result) {
minmaxBonus(a, result);
PairAlg.swapHelper(result); // OK: swapHelper captures the wildcard type
}
public static <T extends Comparable<? super T>> T min(T[] a) {
T smallest = a[0];
for (T t : a) if (t.compareTo(smallest) < 0) smallest = t;
return smallest;
}
}
class PairAlg {
public static boolean hasNulls(Pair<?> p) {
return p.getFirst() == null || p.getSecond() == null;
}
public static void swap(Pair<?> p) { swapHelper(p); }
public static <T> void swapHelper(Pair<T> p) {
T t = p.getFirst();
p.setFirst(p.getSecond());
p.setSecond(t);
}
}
class Pair<T> {
private T first;
private T second;
public Pair() { }
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
class Employee {
private final String name;
private final double salary;
Employee(String name, double salary) { this.name = name; this.salary = salary; }
String getName() { return name; }
double getSalary() { return salary; }
@Override public String toString() { return name; }
}
class Manager extends Employee {
private double bonus;
Manager(String name, double salary) { super(name, salary); }
void setBonus(double bonus) { this.bonus = bonus; }
double getBonus() { return bonus; }
}
ArrayStoreException: Employee
ClassCastException when reading the corrupted pair
Grace Ho and Omar Diaz are buddies.
Lena Park and Grace Ho are buddies.
first: Omar Diaz, second: Grace Ho
first: Grace Ho, second: Omar Diaz
into a Pair<Object>: Omar Diaz
after removeIf: [Lena Park]
earliest: 2024-07-04
copied: [7, 8]
hasNulls: true
swapped: right, left
Common questions
Why is List<Manager> not a List<Employee>, when Manager[] is an Employee[]?
If it were, you could add a plain Employee to a list of managers through the List<Employee> reference. Arrays allow the assignment but check every store at run time, throwing ArrayStoreException. Generic objects don't know their type argument at run time, so the check has to be done at compile time, and the safe rule is "no relationship".
How do I decide between ? extends T and ? super T?
Use PECS: if your method only reads T values from the parameter (a producer), use ? extends T. If it only writes T values into it (a consumer), use ? super T. If it does both, use plain T.
Why can't I add anything to a List<? extends Number>, not even an Integer?
The list could be a List<Double>, and the compiler can't tell. The only value that fits every possible element type is null. If you need to add elements, declare the parameter as List<? super Integer> or List<Number>.
Is List<?> the same as List<Object>?
No. List<Object> holds any objects, and you can add anything to it, but a List<String> can't be passed where a List<Object> is expected. List<?> accepts a list of any element type, but you can only read Object values from it and can add only null.
Should methods return wildcard types?
Generally no. Wildcards in return types force every caller to deal with them. Put wildcards in parameter types to make methods flexible, and return concrete types such as List<T>.
Summary
Pair<Manager>andPair<Employee>are unrelated, whatever the relation betweenManagerandEmployee. Generics are invariant.- Arrays are covariant and protected at run time by
ArrayStoreException. Generic types can't be, because of erasure. - Any parameterized type converts to its raw type, which bypasses checking. Avoid raw types.
ArrayList<T>implementingList<T>makesArrayList<Manager>aList<Manager>, but not aList<Employee>.? extends T: read values asT, write nothing butnull. Use it for producers.? super T: writeTvalues, read onlyObject. Use it for consumers. Remember PECS.<T extends Comparable<? super T>>accepts types likeLocalDatethat inheritcompareTofrom a supertype.?alone: readObject, write onlynull. Fine for operations that don't depend on the type.- Use a generic helper method to capture a wildcard when you need to name its type.
Practice Questions
Why isn't List<Manager> a subtype of List<Employee>?
If it were, you could assign a List<Manager> to a List<Employee> variable and add a plain Employee through it, corrupting the list of managers. Since erasure prevents a run-time check, the compiler must forbid the conversion.
What happens at run time if you store an Employee into an Employee[] variable that actually refers to a Manager[]?
The virtual machine throws an ArrayStoreException, because the array remembers that its element type is Manager.
Given List<? extends Number> nums, which statements compile? (a) Number n = nums.get(0); (b) nums.add(3); (c) nums.add(null);
(a) and (c). Reading as Number is safe, and null belongs to every type. (b) fails, because the list might be a List<Double>.
Write a method that adds the integers 1 to 10 to a list, accepting List<Integer>, List<Number> and List<Object>.
static void fill(List<? super Integer> list) { for (int i = 1; i <= 10; i++) list.add(i); }. The list consumes integers, so use ? super Integer.
Why does Collections.max declare <T extends Object & Comparable<? super T>>?
Comparable<? super T> lets it work with types such as LocalDate whose compareTo comes from a supertype. The extra Object & bound makes T erase to Object, which keeps the erased signature compatible with the pre-generics version of the method.
What is the difference between Pair<?> and the raw type Pair?
Both accept any Pair. With Pair<?>, you can only read values as Object and can't call setFirst except with null, so it's type-safe. The raw Pair lets you call setFirst with any object, silently corrupting the pair.
Why can't swap(Pair<?> p) be written without a helper method?
You can't declare a variable of type ? to hold the first element, and setting p.setFirst(p.getSecond()) fails because the compiler can't prove the captured types match. A generic helper <T> swapHelper(Pair<T> p) gives the unknown type a name, T, so the code type-checks.
Previous: Java Type Erasure: Raw Types, Translation and Bridge Methods
Next: Java Generics Restrictions and Limitations: What You Can't Do with Type Parameters
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.