gpt4 book ai didi

Java获取父类(super class)方法在子类调用时使用子类实例方法

转载 作者:行者123 更新时间:2023-11-30 01:55:15 25 4
gpt4 key购买 nike

我试图让父类(super class)方法在子类调用时在子类方法/字段上运行。例如

public class CoffeeMachine() {
protected int cost = 3;

protected int getCost() {
return cost;
}
}

public class FancyCoffeeMachine() extends CoffeeMachine{
protected int cost = 6;
}

main{
FancyCoffeeMachine expensive = new FancyCoffeeMachine();
System.out.println(expensive.getCost());
}

我希望打印 6,但它却打印 3。我想让它尽可能干燥,所以我试图避免创建第二个 getCost() 方法。有什么办法可以做到这一点吗?当子类调用时,如何获得父类(super class)方法来使用子类变量?方法也会发生同样的事情:如果我有

public class makeCoffee() {
System.out.println("Coffee cost " + this.getCost());
}

即使我在 FancyCoffeeMachine 上调用 makeCoffee,输出也将是“咖啡成本 3”。为什么是这样?我该如何修复它?或者有没有更好的方法来实现这个对象结构,完全避免这个错误?

最佳答案

链接字段不像虚拟方法调用那样使用动态调度。您的字段 FancyCoffeeMachine.cost 只是隐藏字段 CoffeeMachine.cost

要实现您想要的目标(即 FancyCoffeeMachine 具有更高的成本),您只需在 FancyCoffeeMachine 中的初始化程序 block 或构造函数内为 CoffeeMachine.cost 字段设置一个新值即可>.

public class CoffeeMachine {
protected int cost = 3;

protected int getCost() {
return cost;
}
}
public class FancyCoffeeMachine extends CoffeeMachine{
{cost = 6;} // <- sets CoffeeMachine.cost
}

关于Java获取父类(super class)方法在子类调用时使用子类实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54736832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com