普通類的多態(tài)
public class FruitApp {
public static void main(String[] args) {
Fruit f =new Apple(); //聲明時使用多態(tài)
test01(new Apple()); //方法里形參使用多態(tài)
}
public static void test01(Fruit fruit){ //形參使用多態(tài)
}
public static Fruit test02(){
return new Apple(); //返回值使用多態(tài)
}
}
對泛型,是沒有多態(tài)的
/*定義泛型類*/
public class A<T> {
}
public class App {
public static void main(String[] args) {
//A<Fruit> a=new A<Apple>();泛型沒有多態(tài)
A<Fruit> a=new A<Fruit>();
//test01(new A<Apple>());//形參使用多態(tài)錯誤
}
public static void test01(A<Fruit> a){
}
public static A<Fruit> test02(){
//return new A<Apple>; //返回值使用多態(tài)錯誤
}
}
利用通配符,可以實現上面想實現的功能
public class Student<T> {
T score;
public static void main(String[] args) {
Student<?> stu=new Student<String>(); //聲明時使用通配符相當于泛型了,同下面的一樣都是在聲明時
test01(new Student<Integer>());
test02(new Student<Apple>());
//test03(new Student<Apple>()); 錯誤,泛型沒有多態(tài)
}
public static void test01(Student<?> a){ //test01就可以傳入任意指定類型的類了
}
/*此處的test02 則可以傳入Fruit的子類,實現了多態(tài)*/
public static void test02(Student<?extends Fruit> a){
}
/*該方法已經聲明了泛型的具體屬性,在上面調用的時候是沒辦法多態(tài)的*/
public static void test03(Student<Fruit> a){
}
}
泛型的嵌套
public class AhAhut<T> {
T stu;
public static void main(String[] args) {
//泛型的嵌套,下面定義的意思是,AhAhut里面的stu定義為了Student類,而因為
//Student類也有一個泛型需要具體指定,所以就有了嵌套
AhAhut<Student<String>> room=new AhAhut<Student<String>>();
//要取出的話,需要從外到內拆分,先取出Student,再取score
room.stu=new Student<String>();//上面已經指定了Student的具體類型
Student<String> stu=room.stu;
String score=stu.score;
System.out.println(score);
}
}
輸出結果為:null
沒有泛型數組,用通配符可以去替代
public static void main(String[] args) {
Integer[] arr=new Integer[10]; //普通數組
//沒有泛型數組
//Student<String>[] arr2=new Student<String>[10];
Student<?>[] arr2=new Student<?>[10];//可以用問號來創(chuàng)建
//第一個Student的泛型指定為String
Student<String> stu=new Student<>();
stu.score="A";
arr2[1]=stu;
System.out.println(arr2[1].score);
//第一個Student的泛型指定為Integer
Student<Integer> stu2=new Student<>();
stu2.score=20;
arr2[2]=stu2;
System.out.println(arr2[2].score);
}
}
用容器去完成
public class Array {
public static void main(String[] args) {
//具體指定MyArrayList為String
MyArrayList<String> strlist=new MyArrayList<String>();
strlist.add(0, "abc");
String elem=strlist.get(0);
System.out.println(elem);
}
}
/*可以定義一個容器來實現泛型數組的功能*/
class MyArrayList<E>{
//E[] cap=new E[];不能創(chuàng)建泛型數組,
//只能用Object來存,取的時候再轉回去
Object[] cap=new Object[10];
public void add(int idx,E e){
cap[idx]=e; //Object數組可以接收任意類型,所以E類型能進來
}
@SuppressWarnings("unchecked")
public E[] getAll(){
return (E[]) cap; //返回時再轉回去
}
@SuppressWarnings("unchecked")
public E get(int idx){
return (E)cap[idx]; //返回時再轉回去
}
}