Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

9.1 Generic classes — why generics exist

Lesson

A class that works with any type

Suppose you want a box that can hold any kind of object. Without generics you would store an Object — but then you must cast it back on the way out, and the compiler cannot check you. A generic class takes a type parameter (written <T>), so the type is known at compile time: no casts, and mistakes are caught before the program ever runs.


Worked example

class Box<T> {          // T is a placeholder for a real type
    private T item;
    public Box(T item) { this.item = item; }
    public T get() { return item; }
}

Box<String> s = new Box<String>("hello");
Box<Integer> n = new Box<Integer>(42);
System.out.println(s.get().length());   // 5 — a String method, no cast needed

Integer bad = s.get();   // compile ERROR: String cannot be converted to Integer

The same class serves every type, and Box<String> will never hand you an Integer.


▶ Try it: run this — one Box class, two different element types, and a String method called directly on s.get().



In class Box<T>, the T is...


A key benefit of generics over storing Object is...


Type exactly what this program prints.

class Box<T> { private T item; public Box(T i){ item=i; } public T get(){ return item; } }
public class Main { public static void main(String[] a){
    Box<String> b = new Box<String>("hi");
    System.out.println(b.get());
    System.out.println(b.get().length());
}}

Writing Integer n = someBoxOfString.get(); causes...


True or false?