I have below code/classes/interfaces:
An Interface:
public interface Animal<A extends Animal<A>>{
void fight(A otherAnimal);
}
2.Tiger class which is implementing Animal
public class Tiger implements Animal{
@Override
public void fight(Tiger otherAnimal) {
System.out.println("Tiger Fights");
}
}
3. I have a Lion class which also implements Animal
Public class Lion implements Animal{
@Override
public void fight(Lion otherAnimal) {
System.out.println("Lion Fights");
}
I have a test class which is going to call fight:
public class TestClass{
public static void main(String[] args){
Animal tiger = new Tiger();
Animal lion = new Lion();
tiger.fight(lion);
}
}
Now when I run the test class the obvious output is "Tiger Fights".
How should I redesign so that when I call fight on tiger with anything other than tiger should call their respective classes.
So in the example above it should invoke lion's fight even if the fight is called on object of tiger.
I need output as "lion fights" even if I am invoking an object of tiger. Meaning actually I want developer to have freedom to pass any type of object to to any class. My expectation is based on type of object the respective overridden method has to be called.
I need this dynamism because there can be N number of different animals (cat, dog, wolf etc) which might get added in near future.
Is it possible to design in such a way that My Animal interface will decide which class to call depending of type of object passed?
Aucun commentaire:
Enregistrer un commentaire