1
Genericity and its Implementation
Meyer Chapter 10, 16.4
2
Contents
- What is genericity?
- Alternatives:
– multiple instantiation – casting
- Checking correctness of generic types at
definition: constrained genericity
- Subtyping relations between instances
- Implementation of genericity
- Anchor Types
3
What is Genericity?
- We don’t want to write a Stack for Integers, floats,
employees, etc.
– More effort – Versions will become inconsistent, extra debugging effort
- Write once, use for many types
- Implementations:
– C++: templates – Eiffel: constrained genericity – Java: not present, expected in Java 1.5
- Problem: different types allow for different operations.
4
Examples of Genericity
- We have seen Stack[G].
- Vectors of numbers with addition and
- rdering
- A map of (key, element) pairs
- A binary search tree for types that have a ≤
function
5
Two Ideas
- Automatic multiple instantiation (C++)
- Automatic casting
6
The Alternative: Casting
- How do we write a stack in Java?