- Generics are a way to use polymorphism, but specify the class to use in a more restrictive way than Object.
- They are especially useful in the Collection classes, which used to be collections of Object.
- Before Generics, the programmer just had to know what kind of Object was in the collection and then cast it appropriately from Object.
- If the Object was cast to a Point, but it was really some other class, that generates an exception, which had to be caught and handled.
- The basic syntax is to put the class in angle brackets (called a parameterized type), for instance:
ArrayList<String> studentNames = new ArrayList<String>();
- This syntax guarantees that only instances of class String can be added to the list of student names.
- Download the files under generics from downloads to have a look at some code examples. Note: put them in a package called generics