一、正常多态的两种形式
/**
* 多态两种形式
* @author DELL
*
*/
public class FruitApp {
public static void main(String[] args) {
Fruit f = new Apple();
test(new Apple());
}
//形参使用对态
public static void test(Fruit f) {
}
//返回类型使用多态
public static Fruit test2() {
return new Apple();
}
}
二、泛型没有多态
/**
* 泛型没有多态
* @author DELL
*
*/
public class App {
public static void main(String[] args) {
//A<Fruit> f = new A<Apple>(); //这是错误的
A<Fruit> f = new A<Fruit>();
}
//形参使用对态
public static void test(A<Fruit> f) {
}
//返回类型使用多态
public static A<Fruit> test2() {
//return new Apple();
return null;
}
}
三、通配符和泛型实现“类似”多态功能
/**
* ?类型补丁,使用时确定类型
* ?的使用:声明类型,声明方法上,不能声明类或使用时
* ?extends :<=上限 指定类型子类或自身
* ?super :>=下限 指定类型为自身或父类
*
*/
public class Student<T> {
T score;
public static void main(String[] args) {
//编译的时候看左边就是“Student<?>”
Student<?> stu = new Student<String>();
test(new Student<Integer>());
test2(new Student<Apple>());//实现类似多态的功能
//test3(new Student<Apple>()); //泛型没有多态
//test4(new Student<Apple>()); //<因为是小于不可以实现
//test4(stu); //使用时要确定类型
test4(new Student<Object>());
test4(new Student<Fruit>());
}
public static void test (Student<?> stu) {
}
public static void test3 (Student<Fruit> stu) {
}
/**
* <? extends Fruit>实现类似多态
* 是<=
* @param stu
*/
public static void test2 (Student<? extends Fruit> stu) {
}
//>=的概念
public static void test4 (Student<? super Fruit> stu) {
}
}
四、泛型的嵌套
/**
* 泛型的嵌套
* @author DELL
*
*/
public class Bjsxt<T> {
T stu;
public static void main(String[] args) {
//泛型的嵌套
Bjsxt<Student<String>> room = new Bjsxt<Student<String>>();
//从外到内拆分
room.stu = new Student<String>();
Student<String> stu1 = room.stu;
String score = stu1.score;
System.out.println(score);
}
}