Curious Minds

Clear answers to science and history questions

Generics and Inheritance in Java: How They Work

· 6 min read · Science

Generic types and inheritance in Java work together through subtyping rules: a generic class can extend or implement another generic type, and a subtype of a generic class inherits its type parameters and methods, but generic types themselves are not covariant—meaning List<String> is not a subtype of List<Object>. This combination allows you to write reusable, type-safe code that models hierarchical relationships, but it also introduces subtle constraints around type erasure and wildcards that every Java developer encounters.

Background: Why Generics and Inheritance Matter

Before Java 5, collections held Object references, forcing manual casts and risking runtime ClassCastExceptions. Generics, introduced in Java 5, added compile-time type safety by allowing classes and methods to operate on type parameters (e.g., List<String>). Inheritance, a core OOP feature, lets a class derive from another, reusing fields and methods. When combined, they enable patterns like a Repository<T> base class that subclasses specialize for specific entity types, or a Comparable<T> interface that a class implements to define its own ordering. Understanding how they interact is essential for designing clean APIs and avoiding common pitfalls.

How Generic Inheritance Works: Subclassing and Type Parameters

When a class extends a generic class, it can do so in three ways:

  • Pass a concrete type: class StringList extends ArrayList<String> — the subclass is not generic; it inherits methods that use String.
  • Pass a type parameter: class MyList<E> extends ArrayList<E> — the subclass remains generic and passes its own type parameter to the superclass.
  • Pass a wildcard: class OddList extends ArrayList<? extends Number> — rarely used; this restricts the subclass to a specific unknown subtype.

Inherited methods retain the type parameter. For example, if ArrayList<E> has boolean add(E e), then StringList inherits boolean add(String e). The subclass can override such methods, but the override must use the same type—either the concrete type or the type parameter—to match the erasure.

Type Erasure and Its Effect on Inheritance

Java implements generics via type erasure: the compiler removes type parameters and inserts casts where needed, so at runtime a List<String> is just a raw List. This has direct consequences for inheritance:

  • You cannot have two methods that differ only by generic type (e.g., void process(List<String>) and void process(List<Integer>)) because after erasure both become void process(List).
  • You cannot use a type parameter in a static context (e.g., static T instance is illegal) because the type is not known at runtime.
  • You cannot instantiate a type parameter directly (e.g., new T()) because the class is erased.
  • When a subclass overrides a generic method, the compiler may generate a bridge method to handle polymorphism correctly. For example, if StringList overrides add(String), the compiler adds a synthetic add(Object) that casts and delegates.

Wildcards: The Key to Flexible Inheritance

Wildcards (?) allow you to use a generic type without specifying a concrete type, which is crucial when dealing with inheritance hierarchies. The three forms are:

  • ? extends T (upper bound): accepts any subtype of T. Useful for reading from a collection, e.g., void printAll(List<? extends Number> list).
  • ? super T (lower bound): accepts any supertype of T. Useful for writing to a collection, e.g., void addNumber(List<? super Integer> list).
  • ? (unbounded): accepts any type, but you can only read as Object.

Wildcards exist because generic types are invariant: List<Integer> is not a subtype of List<Number>, even though Integer is a subtype of Number. Without wildcards, you couldn't pass a List<Integer> to a method expecting a List<Number>.

How to Choose Between Inheritance and Wildcards

When designing a method that accepts a collection of a subtype, you have two options: use a wildcard or use a generic type parameter. The choice depends on whether you need to refer to the type elsewhere:

  • If you only need to read or write once, use a wildcard: void copy(List<? extends Number> src, List<? super Number> dest).
  • If you need to use the type in multiple places (e.g., return it or store it), use a type parameter: <T extends Number> T max(List<T> list).
  • If you need to both read and write, you must use a concrete type or a type parameter, because wildcards restrict you to one direction.

A common misconception is that List<Object> is a supertype of List<String>. It is not. This is why List<? extends Object> is often used as a safer alternative.

Common Problems and Pitfalls

Developers frequently encounter these issues when mixing generics and inheritance:

  • Raw types: Using a generic class without type arguments (e.g., List list = new ArrayList()) disables type safety and can cause heap pollution.
  • Cannot create arrays of generic types: new List<String>[10] is illegal because arrays are covariant and reified, conflicting with erasure. Use ArrayList<List<String>> instead.
  • Cannot catch generic exceptions: A catch block cannot use a type parameter, because exceptions are checked at runtime and the type is erased.
  • Inheritance with wildcards can be confusing: For example, class A<T> {} and class B extends A<String> {} is fine, but class C extends A<T> {} is illegal unless C also declares T.

Comparisons: Generics vs. Inheritance in Other Languages

Java's approach differs from C++ templates and C# generics. C++ templates are compile-time and reified, meaning each instantiation is a separate type, allowing static methods and type-specific behavior. C# generics are reified at runtime, preserving type information and allowing typeof(T). Java's erasure is a trade-off for backward compatibility—existing non-generic code could still work with generic classes. This means Java cannot do some things that C++ or C# can, like creating arrays of generic types or using type parameters in static contexts, but it simplifies the runtime and maintains compatibility.

Safety and Best Practices

To avoid runtime errors and warnings, follow these guidelines:

  • Always use type parameters or wildcards; never use raw types.
  • Use @SuppressWarnings("unchecked") only when you have verified the cast is safe, and document why.
  • Prefer ? extends for producers (reading) and ? super for consumers (writing), following the PECS principle (Producer Extends, Consumer Super).
  • When extending a generic class, always specify the type argument—either a concrete type or a type parameter—to avoid raw types.
  • Remember that generic type parameters are erased, so never rely on runtime checks like instanceof T.

Frequently Asked Questions

Is List<String> a subtype of List<Object>?

No. Generic types are invariant in Java. Even though String is a subtype of Object, List<String> is not a subtype of List<Object>. If it were, you could add an Integer to a List<String> via a reference to List<Object>, breaking type safety.

Can a generic class extend a non-generic class?

Yes. For example, class MyList<E> extends AbstractList (raw) is allowed, but it's better to extend AbstractList<E> to preserve type safety. A generic class can extend any class, generic or not, as long as it provides appropriate type arguments.

Why can't I create an array of a generic type?

Because arrays are covariant and reified—they know their element type at runtime. Generic types are erased, so the runtime cannot guarantee that an array of List<String> would only contain List<String> elements. This incompatibility is why generic array creation is forbidden.

What is a bridge method?

A bridge method is a synthetic method generated by the compiler to maintain polymorphism after type erasure. For instance, if a subclass overrides a generic method with a concrete type, the compiler adds a bridge method with the erased signature that delegates to the override, ensuring that calls through a superclass reference work correctly.

Can I use a type parameter in a static method?

Yes, but only if the static method declares its own type parameter, e.g., static <T> void print(T item). You cannot use a class's type parameter in a static context because static members belong to the class, not to instances, and the type parameter is not available at runtime.

In this article
  1. Background: Why Generics and Inheritance Matter
  2. How Generic Inheritance Works: Subclassing and Type Parameters
  3. Type Erasure and Its Effect on Inheritance
  4. Wildcards: The Key to Flexible Inheritance
  5. How to Choose Between Inheritance and Wildcards
  6. Common Problems and Pitfalls
  7. Comparisons: Generics vs. Inheritance in Other Languages
  8. Safety and Best Practices
  9. Frequently Asked Questions