Parametric Polymorphism in Java: Generics Flashcards
What is an upper bound on a type parameter?
A class/interface that the type parameter inherits from. example: public class NumberCell
-The extend keyword specifies an upper bound for T
Can be used with both classes and interfaces
- Can have multiple bounds (one class & many interfaces):
T extends MyClass & MyInterface
Does type inheritance implies generic type inheritence?
for example: Integer is an Object, does Cell is a Cell?
No. it’s unsafe.
Legal with arrays, they are covariant.
What is a lower-bound on a type parameter?
What type the parameter can “at-most” be, it has a contra-variance relation.
What is type erasure in Java?
Compiling a Generic class: Cell
- Check type correctness
- Perform Type Erasure: replace T with its upper bound (Object by default). The result is the Raw Type.
- Compile to bytecode
Describe the instantiation process of a generic type in Java
Compiling an instantiation (type): Cell cell;
1. Replace the instantiated type with the raw type
2. “Annotate” generic types with the type arguments
Fields, method arguments and return type, base class/interface
Not regular annotation, but available at runtime using reflection
How java ensures type safety in generics?
Compiling a field access or a message send:
- Obtain the “annotation” of the receiver or method
- Check actual method parameters against the actual type parameters
- Downcast return type to the actual type parameter if needed
Can a virtual method be generic in Java?
Yes. because of type erasure, there is a single instance of the method therefore only one vtable entry needed.
Type Erasure – Pros and Cons
Benefit of Erasure:
- Binary compatibility with older libraries: List is translated to type List (raw type )
Legacy code using “pre-generics” types (e.g. containers) still usable
Drawback of Erasure
- Generic objects carry no type information
List and List refer to the raw List
- No type information inside a generic class/method
Type variables cannot be used in new expressions (can’t do new T(); inside a generic class)
Overload resolution cannot rely on type argument