Lesson 2 of 716 minModule progress 0%

Module 12: Generics and Type Safety

Generic Classes and Interfaces

Create generic classes and interfaces that work with more than one type.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-17

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, manually edited for clarity, and checked against current Java documentation and runnable examples.

Learning goals

  • Declare generic classes correctly
  • Use type parameters consistently inside a class
  • Recognize when a class should be generic at all

A generic class introduces one or more type parameters at the class level: Box<T> means the class works with a placeholder type chosen later.

That placeholder should represent a meaningful role: T is common, but clarity matters more than one-letter tradition when several type parameters exist.

Not every class should be generic: Make a class generic only when the same behavior truly needs to work across different types.

Good design test: If changing the type changes only the data, not the logic, generics probably fit well.

Runnable examples

A simple generic box

class Box<T> {
    private T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }
}

Expected output

The same Box class can store a String, Integer, or any other chosen type safely.

Mini exercise

Create a generic `Pair<A, B>` type with getters for both values.

Summary

  • Generic classes work when behavior stays the same across types.
  • Type parameters should have a clear role.
  • Do not make classes generic without a real reuse reason.

Next step

Next, add type parameters at the method level when only one operation needs them.

Sources used

Advertisement

Lesson check

When does a generic class make sense?

Next lesson →