Generics • Java allow you to define generic classes, interface, and methods <Prior to JDK 1. 5> Comparable c = new Date(); System. out. println(c. compare. To(“red”)); <JDK 1. 5> Comparable<Date> c = new Date(); System. out. println(c. compare. To(“red”)); Compile 會過 但執行會錯 因為Date與String 型態不符 Compile 時會檢查 Date與String型態 是否符合
Defining Generic Classes and Interfaces 程式範例: Generic. Stack. java
使用Generic type 優點: Certain errors can be detected at compile time rather than at runtime. 易犯的錯: Constructor of Generic. Stack should be defined as (X) (O) public Generic. Stack<E>() public Generic. Stack()
A wildcard generic type has three forms : 1. ? Unbounded wildcard (same as ? extends Object) 2. ? extends T bounded wildcard 3. ? super T lower-bound wildcard (T is generic type)