Skip to content

Are there any types that cannot have type parameters? #8

@ThomsonTang

Description

@ThomsonTang

All types, except enum types, anonymous inner classes and exception classes, can be generic...

Almost all reference types can be generic. This includes classes, interfaces, nested (static) classes, nested interfaces, inner (non-static) classes, and local classes.

The following types cannot be generic:

  • Anonymous inner classes: They can implement a parameterized interface or extend a parameterized class, but they cannot themselves be generic classes. A generic anonymous inner class would be nonsensical. Anonymous class do not have a name, but the name of a generic class is needed for declaring an instantiation of the class and providing the type arguments. Hence, generic anonymous classes would be pointless.
  • Exception types: A generic class must not directly or indirectly be derived from class Throwable. Generic exceptions or errors are disallowed because the exceptions handling mechanism is a runtime mechanism and the Java virtual machine doesn't know anything about Java generics. The JVM would not be capable of distinguishing between different instantiation of generic exception types. Hence, generic exception types would be pointless.
  • Enum types: Enum type cannot have type parameters. Conceptually, an enum and its enum values are static. Since type parameters cannot be used in any static context, the parameterization of an enum type would be pointless.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions