Java泛型的无多态,?通配符,泛型嵌套,无多态数组(四)

一、正常多态的两种形式

/**
 * 多态两种形式
 * @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);
		
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值