Method overloading, why supertype must be cast
Trying to refactor some code and I stumbled on a problem that can be
demonstrated by the following code:
public static abstract class Animal {
public abstract void attack(Animal other);
}
public static class Cat extends Animal {
@Override
public void attack(Animal other) {
catAttack(other); <-------- Problem here
}
private void catAttack(Cat other) {
// Maybe a meow showdown wins the fight, no need to get physical
}
private void catAttack(Dog other) {
// Dogs are dangerous, run!
}
}
public static class Dog extends Animal {
@Override
public void attack(Animal other) {
}
}
Why is it that the specific type of other in catAttack(other) cannot be
found so that the most specific method can be called? Instead this check
must be done:
if (other instanceof Cat)
catAttack((Cat) other);
if (other instanceof Dog)
catAttack((Dog) other);
No comments:
Post a Comment