Parametric Polymorphism in Java: Generics Flashcards

1
Q

What is an upper bound on a type parameter?

A
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Does type inheritance implies generic type inheritence?

for example: Integer is an Object, does Cell is a Cell?

A

No. it’s unsafe.

Legal with arrays, they are covariant.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a lower-bound on a type parameter?

A

What type the parameter can “at-most” be, it has a contra-variance relation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is type erasure in Java?

A

Compiling a Generic class: Cell

  1. Check type correctness
  2. Perform Type Erasure: replace T with its upper bound (Object by default). The result is the Raw Type.
  3. Compile to bytecode
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Describe the instantiation process of a generic type in Java

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How java ensures type safety in generics?

A

Compiling a field access or a message send:

  1. Obtain the “annotation” of the receiver or method
  2. Check actual method parameters against the actual type parameters
  3. Downcast return type to the actual type parameter if needed
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can a virtual method be generic in Java?

A

Yes. because of type erasure, there is a single instance of the method therefore only one vtable entry needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Type Erasure – Pros and Cons

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly