Generics: a stronger typization in Java5From WikiJavabuy this book
The Apple and Pear class are full working examples. The TestApplePear class is a NOT working example, to show you the single most advantage from a stronger typization: a run-time error from the compiler.
the articleComparable is a typical example of generic interface because it has a parameter of type T. <T> is a declaration of formal parameter of type. After that declaration, T could be used in the code as a known type. A generic class could be instantiated as in the following examples, and it will be clear that we can't compare pears and apples. Eheheh. Comparable.javapublic interface Comparable<T> { int compareTo(T o); } Apple.javapublic class Apple implements Comparable<Apple>{ private int weight; private String type; public Apple(String type, int weight) { this.type = type; this.weight = weight; } public int compareTo(Apple m){ // we don't have to use an explicit cast return weight - p.weight; } } Pear.javapublic class Pear implements Comparable<Pear>{ private int weight; private String type; public Pear(String type, int weight){ this.type = type; this.weight = weight; } public int compareTo(Pear p){ // we don't have to use an explicit cast return weight - p.weight; } } TestApplePear.javapublic class TestApplePear{ public static void main (String [] args){ Apple apple = new Apple("golden",135); Pear pear = new Pear("williams",120); int comp = pear.compareTo(apple); // compilation error } }
|
