Advertisement
Intermediate Java, Inner Classes & Anonymous Classes

Can a local class or anonymous class be generic, and how does its own type parameter interact with any generic type parameters already declared on its enclosing class or method?

Short answer

Yes, a local class can declare its own generic type parameters just like a top-level class, and it can also freely reference generic type parameters already in scope from its enclosing class or enclosing generic method -- an anonymous class, however, CANNOT declare its own NEW…

Save Java mock interview
Advertisement
AModel answer
Yes, a local class can declare its own generic type parameters just like a top-level class, and it can also freely reference generic type parameters already in scope from its enclosing class or enclosing generic method -- an anonymous class, however, CANNOT declare its own NEW generic type parameters (there's no syntax to do so, since an anonymous class is defined via an expression, not a full class declaration), though it can still be a parameterized instantiation of an already-generic interface or class (like `new Comparator<String>() { ... }`) and can access generic type parameters from its enclosing scope.
public <T> List<T> processItems(List<T> items) {
    class Wrapper<U> {  // local class with its OWN new generic type parameter U
        U wrapped;
        Wrapper(U value) { wrapped = value; }
    }
    Wrapper<String> w = new Wrapper<>("example");

    // Anonymous class: parameterizes an EXISTING generic interface, doesn't declare a NEW type parameter itself
    Comparator<T> comparator = new Comparator<T>() {  // uses enclosing method's T, no new parameter introduced
        public int compare(T a, T b) { return 0; }
    };
    return items;
}
Real-world example
A generic utility method defines a local class with its own additional generic type parameter to build an internal helper structure distinct from the method's own type parameter, demonstrating that local classes have full generic class capabilities unlike the more syntactically limited anonymous class form.
Likely follow-ups
  • Why specifically can't an anonymous class declare a new generic type parameter of its own, given it can still reference existing ones from its enclosing scope?
  • How would you work around this anonymous class limitation if you genuinely needed a new type parameter, perhaps by using a local class instead?
Related topics