java 调用重载方法_在Java中调用哪个重载方法

特定于问题的解决方案

在某些语言中,参数被解析为其动态类型,但不是在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 方法,该方法使用正确的(动态)类型 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值