我是泛型新手。这是我的课。
public interface Animal {
void eat();
}
public class Dog implements Animal {
public void eat() {
System.out.println("Dog eats biscuits");
}
}
public class Cat implements Animal {
public void eat() {
System.out.println("Cat drinks milk");
}
}
现在我希望以通用的方式使用这些类。
public class GenericExample {
public <T extends Animal> T method1() {
//I want to return anything that extends Animal from this method
//using generics, how can I do that
}
public <T extends Animal> T method2(T animal) {
//I want to return anything that extends Animal from this method
//using generics, how can I do that
}
public static void main(String[] args) {
Dog dog = method1(); //Returns a Dog
Cat cat = method2(new Cat()); //Returns a Cat
}
}
如何从方法“method1”和“method2”返回泛型类型(可能是 Cat 或 Dog)。我有几个这样的方法返回“T extends Animal”,所以在方法级别或类级别声明泛型类型更好。