Can anyone please help how I can call a method (eat
) of an child class (Tiger
) externally by passing the instance of the child class (tiger
) but the argument type is of parent class (Animal
) and the parent calls has no method defined.
I have a requirement where I cannot make changes to the ParentClass as its a third-party class
Meaning the following code breaks (where parent class has no defined method eat
):
package learnings;
import static java.lang.System.out;
abstract class BaseAnimal {
}
class Tiger extends BaseAnimal {
public String eat(String x) {
out.printf("Tiger eats %s\n", x);
return x;
}
}
class Lion extends BaseAnimal {
public String eat(String x) {
out.printf("Lion eats %s\n", x);
return x;
}
}
public class LearnJavaGenerics2 {
// simple example of generic with bounded type
// Same error with public static void callEat(BaseAnimal animal, String y) {
public static <T extends BaseAnimal> void callEat(T animal, String y) {
out.printf("animal Type: %s\n", animal);
animal.eat(y);
}
public static void main(String[] args) {
Lion lion = new Lion();
Tiger tiger = new Tiger();
callEat(lion, "foo");
callEat(tiger, "bar");
}
}
With Exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method eat(String) is undefined for the type T
at learnings.LearnJavaGenerics2.callEat(LearnJavaGenerics2.java:31)
at learnings.LearnJavaGenerics2.main(LearnJavaGenerics2.java:37)
But the following code passes (where parent class has a defined method):
package learnings;
import static java.lang.System.out;
abstract class BaseAnimal {
public String eat(String x) {
out.printf("BaseAnimal eats String %s\n", x);
return x;
}
}
class Tiger extends BaseAnimal {
public String eat(String x) {
out.printf("Tiger eats %s\n", x);
return x;
}
}
class Lion extends BaseAnimal {
public String eat(String x) {
out.printf("Lion eats %s\n", x);
return x;
}
}
public class LearnJavaGenerics2 {
// simple example of generic with bounded type
public static <T extends BaseAnimal> void callEat(T animal, String y) {
out.printf("animal Type: %s\n", animal);
animal.eat(y);
}
public static void main(String[] args) {
Lion lion = new Lion();
Tiger tiger = new Tiger();
callEat(lion, "foo");
callEat(tiger, "bar");
}
}
With Output:
animal Type: learnings.Lion@1b6d3586
Lion eats foo
animal Type: learnings.Tiger@4554617c
Tiger eats bar