I’m new to generics. Here are my classes.
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");
}
}
Now I want these classes to be used in a generic way.
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
}
}
How can I return the generic type (may be a Cat or Dog) from the methods “method1” and “method2”. I’ve several such methods that returns “T extends Animal”, so is it better to declare the generic type in a method level or class level.
You cannot have a method returning a generic type, and expect to be able to access that type in the caller of the method without a cast, unless that type can be deduced from the arguments to the method. So the examples in your
mainwon’t work.So you either go without generics, and either cast the return type manually
or have the method return the subclass type to start with.
Or you can go with generics, and either specify the type when calling the method
or pass some argument from which the type can be deduced (which the second method already satisfies):
Also nituce that you only can call
method1fromstatic mainif it isstaticitself.