I have below code/classes/interfaces with me:
An Interface:
public interface Animal{
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 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 ?
I really appreciate if some one can provide their answers with code snippets. Sorry about my bad English.
Aucun commentaire:
Enregistrer un commentaire