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?
13
First of all, you’re setting up Animal
interface with generics in order to make the Animal
instance passed to fight as the same as the one implementing Animal
. In other words, Lion
can only fight a Lion
. A Tiger
can only fight a Tiger
. From the sounds of it, you want to be able to fight any animal. If you don’t need to use A for any other reason in interface, ditch it. It isn’t helpful.
public interface Animal {
void fight(Animal otherAnimal);
}
Second, now that you’re receiving an Animal
instance, you need to know if it is an instance of the very same class implementing Animal
.
To do this, you could simply write:
public class Tiger implements Animal{
@Override
public void fight(Animal otherAnimal) {
if(otherAnimal.getClass().equals(this.getClass()) {
System.out.println("Two tigers fight");
} else {
System.out.println("Tiger fights a " + otherAnimal.getClass().getName());
}
}
}
This works fine so long as you don’t need to know what type otherAnimal
is. In other words, if you start constructing if.. else lists to cover every possibility, you’re doing it wrong. Tiger should know how it fights other animals, and anything that might change the outcome should be something that all Animal
instances have.
For instance, if you want to attack “Pokemon” style with each animal having its own health bar, you need not cast it to Lion
to get the Lion
‘s health points. You need only create a “getHealthPoints” method in Animal
.
If you’re using Java 8, you can even make use of defaults in your interface and override only if your subclass needs to behave differently:
public interface Animal {
default void fight(Animal otherAnimal) {
if(otherAnimal.getClass().equals(this.getClass()) {
System.out.println("Two " + this.getClass().getName() + "s fight");
} else {
System.out.println(this.getClass().getName() + " fights a " + otherAnimal.getClass().getName());
}
}
}
For this particular example, this should be sufficient, though if you’re looking for an example of Visitor pattern, the wikipedia article on Visitor pattern provides a decent explanation. Note that the structure is more hierarchical and serves primarily for performing an operation on each object in it. This would be a bit of an overkill for this particular instance, so I won’t modify the above example.
Hope that helps.
If you are looking for a class for code that calls a winner of 2 animals fighting, then the solution is a third class that does that. Imagine you have to write a compare
method that compares objects of 10 very different classes. Obviously you can’t have code doing the comparing spread out all over those 10 classes. It’s much cleaner to write a Comparator
class.
If you are just asking how to write code x operation y
where you can code operation
for each x
and y
type pair separately then you’re looking for dual dispatch, usually implemented by Visitor
pattern.
Edit: you are also misusing generic types. You are adding generic type of A to whole Animal type just for the target type of fight method. You should add generic type to the method only.
The correct declaration of animal would be:
public interface Animal {
<A extends Animal> void fight(A otherAnimal);
}
1
From what you wrote, it is still a little bit unclear what you are after, but I guess when a “Tiger” fights a “Lion”, you do not want to have printed “Tiger fights” or “Lions fights”, but something like “Tiger fights Lion”. And that is nothing for which you need double dispatch or the visitor pattern.
Just separate the “output part” from the “who fights” part:
public interface Animal {
String Race();
int Strength();
}
public class Tiger implements Animal{
@Override
public String Race() {
return "Tiger";
}
@Override
public int Strength() {
return 10;
}
(yes, the Race
part could be more elegantly implemented by using this.getClass().getName()
, but this is for demonstration purposes). I have added an additional Strength
method to make clearer how this works and how to implement actual logic with it. Place the fight method (the output part) somewhere else, and implement it in terms of “Animals”:
public class Arena {
public void fight(Animal a1, Animal a2) {
System.out.println(a1.Race() + " fights " + a2.Race());
if(a1.Strength()>a2.Strength)
{
System.out.println(a1.Race() + " wins");
}
else if(a1.Strength()<a2.Strength)
{
System.out.println(a2.Race() + " wins");
}
else
{
System.out.println("Tie.");
}
}
Now you can easily add more different animals, without touching any of the existing animal classes or touching the fight
method.
2