06 Generics
06 Generics
Motivation
Genericity
Kinds of Genericity
Generic Classes
Genericity in Java
Summary
Motivation
Important qualities of software systems
Reusability
The ability of software elements to serve for the construction of
many different applications.
Extendibility
The ease of adapting software products to changes of
specification.
To yield a higher degree of extendibility and reusability the class
construct must be more flexible!!
Two directions
Abstraction and specialization
realized by means of inheritance
Type parameterization
known as genericity
© Horst Lichter, RWTH Aachen 2
Extension Alternatives
Inheritance Abstraction
Set
OfCars
LinkedList
OfCars
Specialization
What
happens if
Point p = new Point();
we are
Rectangle r = new Rectangle();
wrong?
List geoObjects = new ArrayList();
geoObjects.add(p);
geoObjects.add(r);
Point p1 = (Point)geoObjects.get(0);
Rectangle r1 = (Rectangle)geoObjects.get(1);
class ArrayList<E> {
boolean contains (E element) {…}
void add(int index, E element){…}
boolean isEmpty() {…}
…
} Actual generic parameter
...
end
generic deviation
© Horst Lichter, RWTH Aachen 16
Generic Methods
A method which declares a type variable
type variable
lo.add(new Object()); // 3
String s = ls.get(0); // 4
In general:
If B is a subtype of A, and G is some generic type declaration, it is
not the case that G<B> is a subtype of G<A>.