CodeBlanks Logo Icon CodeBlanks

Summary - Generics

Combine generic class and method to write a Box<T>.

Summary - Generics

In this group you learned generics: generic class and method with <T>, bounded type with <T extends Number>, wildcards ? extends T and ? super T, and finally type erasure. Generics give compile-time type safety; at runtime the type is erased.

In this summary we will combine everything into a Box<T> class and a Box.of generic factory method. You will see generic class features, generic method type inference and the diamond operator together.

Practice Box<T> class and Box.of method

Define class Box<T> with a T value field, a Box(T value) constructor and a static <T> Box<T> of(T value) generic factory method whose body is return new Box<>(value);. In main, instantiate with Box<String> b = Box.of("Notebook"); and print it with System.out.println(b.value);.

Starter code

Main.java
// Define the Box<T> generic class (T value field, constructor)

// Add the Box.of generic method

// main: instantiate via Box.of and print with println

Sample solution

Main.java
class Box<T> {
    T value;
    Box(T value) { this.value = value; }
    static <T> Box<T> of(T value) {
        return new Box<>(value);
    }
}

public class Main {
    public static void main(String[] args) {
        Box<String> b = Box.of("Notebook");
        System.out.println(b.value);
    }
}

Expected output

Notebook

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the core benefit of generics?

  • Compile-time type safety Correct answer
  • Keeping type info at runtime
  • Running code faster
  • Removing reflection

Explanation: Generics give compile-time type safety; at runtime the type is erased.

2 Complete the generic factory method

Question
static <T> Box____ of(T value) {
    return new Box<>(value);
}
Answer
static <T> Box<T> of(T value) {
    return new Box<>(value);
}

Explanation: <T> gives the Box class its type parameter.

3 Match the generics summary

Term Meaning
<T> Type parameter
<T extends Number> Bounded type
? extends T Producer wildcard
Box.of Generic factory method

All lessons in Intermediate