Instantiating Generic Classes with Type Arguments
What you'll learn: How to create actual instances of generic classes by specifying concrete types.
Now that you've learned to declare a generic class (like Box<T>), it's time to actually use it. When you create an instance of a generic class, you replace the type parameter with a real, concrete type—this is called a type argument.
The Core Idea
Think of a generic class declaration as a blueprint with a blank space for a type. When you instantiate it, you fill in that blank with a specific type like String, Integer, or any other class. This tells Java exactly what kind of data your instance will work with.
Syntax
ClassName<TypeArgument> variableName = new ClassName<TypeArgument>();
For example, if you have a generic Box<T> class:
Box<String> stringBox = new Box<String>();
Box<Integer> intBox = new Box<Integer>();
Box<Double> doubleBox = new Box<Double>();
Each variable is now a different type: stringBox works only with String values, intBox only with Integer, and so on. The compiler enforces this type safety.
Why This Matters
By providing concrete type arguments at instantiation, you:
- Get compile-time type safety: The compiler prevents you from putting an
Integerinto aBox<String> - Eliminate casting: No need to cast objects when retrieving them
- Create multiple specialized versions from a single generic class definition
Analogy
It's like ordering a custom-made container: the manufacturer (generic class) asks "What will you store?" You answer "books" (Box<String>) or "tools" (Box<Integer>). Once built, that container is specialized for your choice.
Key Takeaway: You instantiate generic classes by providing concrete type arguments in angle brackets, creating type-safe instances tailored to specific data types.