上一篇 Java 泛型詳解(一)介紹了泛型的引出、定義和使用,已經泛型的通配符。下面繼續介紹泛型接口和f泛型方法。
一、泛型接口
使用泛型定義的接口可以稱爲泛型接口。例如:
interface Message<T> { // 泛型接口
public String getInfo(T msg) ;
}
泛型接口的實現,在Java之中有兩種方式:
(1)在子類上繼續定義泛型,同時此泛型在接口上繼續使用、例:
interface Message<T> { // 泛型接口
public String getInfo(T msg);
}
class MessageImpl<T> implements Message<T> {
public String getInfo(T msg) {
return "info : " + msg;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Message<String> msg = new MessageImpl<String>();
System.out.println(msg.getInfo("張三"));
}
}
運行結果:
info : 張三
(2)在子類上設置具體類型:
interface Message<T> { // 泛型接口
public String getInfo(T msg);
}
class MessageImpl implements Message<String> {
public String getInfo(String msg) {
return "info : " + msg;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Message<String> msg = new MessageImpl();
System.out.println(msg.getInfo("張三"));
}
}
運行結果:
info : 張三
二、泛型方法
泛型除了可以定義在類上之外,也可以在方法上進行定義,而在方法上定義泛型的時候,這個方法不一定非要在泛型類中定義。
例1:
public class Test {
public static void main(String[] args) throws Exception {
String str = fun("hello world");
System.out.println(str.length());
}
//T的類型由傳入的參數類型決定
public static <T> T fun(T t){
return t;
}
}
運行結果:
11
例二:
public class Test {
public static void main(String[] args) throws Exception {
Integer result[] = get(1, 2, 3);
for (int temp : result) { // 連自動拆箱都包含了
System.out.println(temp);
}
}
public static <T> T[] get(T... args) { // T的類型由方法調用的時候來決定
return args;
}
}
運行結果:
1
2
3
三、泛型小結:
泛型的好處是在編譯的時候檢查類型安全,並且所有的強制轉換都是自動和隱式的,以提高代碼的重用率。