当子类调用时,我试图让超类方法在子类方法/字段上运行。例如
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。我想让它尽可能 DRY,所以我试图避免创建第二个 getCost() 方法。有没有办法做到这一点?当子类调用时,如何获得使用子类变量的超类方法?方法也会发生同样的事情:如果我有
public class makeCoffee() {
System.out.println("Coffee cost " + this.getCost());
}
即使我在 FancyCoffeeMachine 上调用 makeCoffee,输出也会是“Coffee cost 3”。为什么是这样?我该如何解决?或者有没有更好的方法来实现这个完全规避这个错误的对象结构?
呼啦一阵风
慕容3067478
慕标5832272
炎炎设计
慕雪6442864
随时随地看视频慕课网APP
相关分类