特定于问题的解决方案
在某些语言中,参数被解析为其动态类型,但不是在java中 . 编译器已经在编译时确定了 getWorkDetail(this); 将要去的地方 . this 的类型为 Person ,因此调用 getWorkDetail(Person e) . 在您的具体情况下,解决方案非常明显 . 正如其他人已经指出的那样,你需要在 Employee 类中覆盖 getWorkDetail() .
解析其动态参数类型的方法
要解决在运行时解析参数类型的一般问题,应避免使用 instanceof 运算符,因为它通常会导致不干净的代码 .
如果您有两个不同的类,则无法再实现上述简单的解决方案 . 在这些情况下,您将不得不使用visitor pattern .
考虑以下类:
public interface Animal {
default void eat(Food food) {
food.eatenBy(this);
}
void eatMeat(Meat meat);
void eatVegetables(Vegetables vegetables);
}
public class Shark implements Animal {
public void eatMeat (Meat food) {
System.out.println("Tasty meat!");
}
public void eatVegetables (Vegetables food) {
System.out.println("Yuck!");
}
}
public interface Food {
void eatenBy(Animal animal);
}
public class Meat implements Food {
public void eatenBy(Animal animal) {
animal.eatMeat(this);
}
}
public class Vegetables implements Food {
public void eatenBy(Animal animal) {
animal.eatVegetables(this);
}
}
你可以这样打电话:
Animal animal = new Shark();
Food someMeat = new Meat();
Food someVegetables= new Vegetables();
animal.eat(someMeat); // prints "Tasty meat!"
animal.eat(someVegetables); // prints "Yuck!"
在 visitor pattern 之后调用 Animal.eat 将调用 Food.eatenBy ,它由 Meat 和 Vegetables 实现 . 这些类将调用更具体的 eatMeat 或 eatVegetables 方法,该方法使用正确的(动态)类型 .