泛型,可以是任意类型,但是我们有时候,需要限制类型,这样更加安全。
新建一个Animal类,然后再搞两个子类Dog和Cat类:
package com.java1234.chap06.sec02; public class Animal { public void print(){ System.out.println("动物"); } }
package com.java1234.chap06.sec02; public class Dog extends Animal{ public void print(){ System.out.println("Dog"); }
package com.java1234.chap06.sec02; public class Cat extends Animal{ public void print(){ System.out.println("Cat"); } }
然后我们定义一个泛型类:
package com.java1234.chap06.sec02; public class Demo <T extends Animal>{ private T ob; public T getOb() { return ob; } public void setOb(T ob) { this.ob = ob; } public Demo(T ob) { super(); this.ob = ob; } public void print(){ System.out.println("T的类型是:"+ob.getClass().getName()); } }
测试类:
package com.java1234.chap06.sec02; public class Test { public static void main(String[] args) { Demo<Dog> demo=new Demo<Dog>(new Dog()); Dog dog=demo.getOb(); dog.print(); Demo<Cat> demo2=new Demo<Cat>(new Cat()); Cat cat=demo2.getOb(); cat.print(); Demo<Animal> demo3=new Demo<Animal>(new Animal()); } }
运行输出:
Dog
Cat