默认创建的类型是没有任何限制的,如果想显示泛型的数据类型,通过extends关键字指定该类型必须是继承某个类或者实现某个接口,这时候泛型就被限制在父类及其所有子类或者接口及其实现类中的数据类型范围中。
A<T extends B>
A<T ectends Iinfo>
Demo1:T extends superClass
package Genericity;
public class GenericDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericClass<Dog> dogClass=new GenericClass<Dog>();
Dog objDog=new Dog();
dogClass.setObj(objDog);
dogClass.getObj().eat();
GenericClass<Cat> catClass=new GenericClass<Cat>();
catClass.setObj(new Cat());
catClass.getObj().eat();
}
}
//泛型类所接收的参数做了限制,只能接收Animal类型及其子类的数据
class GenericClass<T extends Animal>{
private T obj;
public T getObj() {
return obj;
}
public void setObj(T obj) {
this.obj = obj;
}
}
abstract class Animal{
public abstract void eat();
}
class Dog extends Animal{
public void eat(){
System.out.println("eating bones");
}
}
class Cat extends Animal{
public void eat(){
System.out.println("eating fish");
}
}
Demo2:T extends Interface
package Genericity;
public class GenericDemo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
GenericClass<Dog> dogClass=new GenericClass<Dog>();
Dog objDog=new Dog();
dogClass.setObj(objDog);
dogClass.getObj().eat();
GenericClass<Cat> catClass=new GenericClass<Cat>();
catClass.setObj(new Cat());
catClass.getObj().eat();
}
}
//泛型类限制类型于接口仍然用extends关键字
//泛型类现在仅限制使用IAnimal实现的类型数据
class GenericClass<T extends IAnimal>{
private T obj;
public T getObj() {
return obj;
}
public void setObj(T obj) {
this.obj = obj;
}
}
interface IAnimal{
public abstract void eat();
}
class Dog implements IAnimal{
public void eat(){
System.out.println("eating bones");
}
}
class Cat implements IAnimal{
public void eat(){
System.out.println("eating fish");
}
}