java中的泛型是伪泛型。
package com.gaofeng.day03;
import java.util.ArrayList;
public class Demo06 {
public static void main(String[] args) {
ArrayList<Ye> list1 = new ArrayList<>();
ArrayList<Fu> list2 = new ArrayList<>();
ArrayList<Zi> list3 = new ArrayList<>();
ArrayList<Student> list4 = new ArrayList<>();
/**
* 接受任意类型的参数
* 泛型通配符
*/
method(list1);
method(list2);
method(list3);
/**
* 传递指定类型的参数
*/
method2(list1);
// method2(list3);
method2(list2);
// method2(list4);
}
public static <E> void method(ArrayList<E> list){
}
/**
* extends E 表示只能接受E类型或者E类型的子类
* super E 表示只能接受E类型或者E类型的父类
* @param list
*/
public static void method2(ArrayList<? super Fu> list){
}
}
class Ye{}
class Fu extends Ye{}
class Zi extends Fu{}
class Student{}
package com.gaofeng.day03;
import java.util.ArrayList;
public class Demo07 {
public static void main(String[] args) {
ArrayList<LihuaCat> list1 = new ArrayList<>();
ArrayList<PersianCat> list3 = new ArrayList<>();
ArrayList<Husky> list2 = new ArrayList<>();
ArrayList<Teddy> list4 = new ArrayList<>();
keepPet(list1);
keepPet(list3);
keepPet(list2);
keepPet(list4);
keepPet2(list1)
keepPet2(list3);
keepPet2(list2);
keepPet2(list4);
}
/**
* 只能养猫,不能养狗
* @param list
*/
public static void keepPet(ArrayList<? extends Cat> list){
}
/**
只能养狗,不能养猫
*/
public static void keepPet2(ArrayList<? extends Dog> list){
}
/**
* 只能是动物类,其他类不行
*/
public static void keepPet3(ArrayList<? extends Animal> list){
}
}
abstract class Animal{
private String name;
private int age;
public Animal(){}
public Animal(String name, int age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public abstract void eat();
@Override
public String toString(){
return "Animal{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
abstract class Cat extends Animal{
}
class PersianCat extends Cat{
@Override
public void eat() {
System.out.println(getName() + "PersianCat eat" + getAge() + "岁的波斯猫,正在吃饼干");
}
}
class LihuaCat extends Cat{
@Override
public void eat() {
System.out.println(getName() + "LihuaCat eat" + getAge() + "岁的狸花猫,正在吃鱼");
}
}
abstract class Dog extends Animal{
}
class Teddy extends Dog{
@Override
public void eat() {
System.out.println(getName() + "Teddy eat" + getAge() + "岁的泰迪,正在吃骨头");
}
}
class Husky extends Dog{
@Override
public void eat() {
System.out.println(getName() + "Husky eat" + getAge() + "岁的哈士奇,正在吃肉");
}
}