Type Parameter Scope: Class-Level vs Method-Level
What you'll learn: You'll understand where type parameters are visible and how class-level and method-level type parameters differ in scope.
The Core Idea
Type parameters can be declared in two places with different visibility rules:
Class-level type parameters are declared on the class itself and are visible throughout the entire class—in all instance fields, constructors, and methods. These parameters represent types that apply to the whole object.
Method-level type parameters are declared on individual methods and exist only within that specific method's scope. They're independent of any class-level type parameters, even if they use the same letter.
Understanding Scope Boundaries
Think of class-level type parameters like a house's address—every room (method) in the house shares that same address. Method-level type parameters are like room-specific features that only exist in one room.
public class Container<T> { // T is class-level
private T item; // Uses class-level T
public Container(T item) { // Uses class-level T
this.item = item;
}
public T getItem() { // Uses class-level T
return item;
}
// Method-level type parameter U
public <U> void process(U input) { // U is method-level only
// U is visible only inside this method
// T (class-level) is also visible here
}
public <T> void example(T param) { // This T shadows class T!
// Method-level T hides the class-level T in this method
}
}
When you instantiate Container<String>, the class-level T becomes String for that entire object. But each call to process can use a different type for U.
Key Takeaway: Class-level type parameters span the entire class and define the object's type identity, while method-level type parameters are local to individual methods and independent of the class's types.