ReviseAlgo Logo

Generics

Generic Classes

Analyze generic class declarations, parameterized instantiations, and static context type constraints.

Interview: Focuses on class declarations, parameter scopes, instantiating generic variables, and static variable constraints.

Last Updated: June 13, 2026 10 min read

A Generic Class is a class that parameterizes its type references. It allows class fields, constructor arguments, and method return values to be typed dynamically by the client at instantiation.

Type Parameters

Declared in class headers using angle brackets: class Box<T>. Multiple parameters are comma-separated.

Dynamic Fields

Instance variables can be declared using the parameter: private T value;.

Static Limits

Static fields and methods cannot reference class-level type parameters, as static members are shared across all instances.

Static Context Restrictions

Class-level type parameters cannot be accessed from static scopes:

  • Static Fields: Code like private static T sharedValue; is illegal. Because static fields are shared across instances, they cannot have distinct generic types.
  • Static Methods: Cannot refer to class-level parameters: public static T get() is invalid. However, static methods can declare their own independent type parameters.

Common Pitfalls

  • Declaring static fields with class parameters: Writing static T field;, which causes a compile-time error.
  • Trying to instantiate T directly: Writing T val = new T(); inside constructors. This is forbidden because type erasure removes type information at runtime.

Best Practices

  • Use standard naming letters: Adhere to conventions: T (Type), E (Element), K (Key), V (Value), N (Number).
  • Keep classes focused: Limit generic classes to single-purpose data structures or processors.

Interview-Relevant Information

Q1: Why can static methods or fields not use class-level type parameters?
Answer: Static members belong to the class rather than individual instances. Because different instances can have different type arguments (e.g. Box<String> vs Box<Integer>), static members cannot determine which type argument to use.

Q2: Can you instantiate a generic type parameter (e.g. new T())?
Answer: No. Instantiation requires concrete type information at runtime, which is removed by type erasure. To instantiate types dynamically, you must pass a factory or a Class<T> reference and use reflection.

Quick Checklist

Can you write a generic class definition, explain why static fields cannot access type parameters, and explain why new T() is invalid? If yes, you understand generic classes.

Use Cases

Building generic API response wrappers that encapsulate status codes and payload entities.

Creating type-safe custom collections and cache buffers.

Common Mistakes

Referencing class-level type parameters within static variables.

Attempting to instantiate type parameters directly in constructors.