4 回答

TA貢獻1773條經驗 獲得超3個贊
鏈接字段不像虛擬方法調用那樣使用動態調度。您的字段FancyCoffeeMachine.cost只是隱藏了該字段CoffeeMachine.cost。
要實現您想要的(即具有更高成本的 FancyCoffeeMachine),您可以簡單地CoffeeMachine.cost為初始化塊或構造函數中的字段設置一個新值FancyCoffeeMachine。
public class CoffeeMachine {
protected int cost = 3;
protected int getCost() {
return cost;
}
}
public class FancyCoffeeMachine extends CoffeeMachine{
{cost = 6;} // <- sets CoffeeMachine.cost
}

TA貢獻1966條經驗 獲得超4個贊
您正在getCost
從超類(CoffeeMachine)調用方法,因為您的子類(FancyCoffeeMachine)中沒有它。而且您的超類對 subclass 及其字段一無所知cost
。您還應該覆蓋方法getCost
以使其像您描述的那樣工作。

TA貢獻1808條經驗 獲得超4個贊
我很確定你也必須覆蓋getCost()。FancyCoffeeMachine
public class FancyCoffeeMachine() extends CoffeeMachine{
protected int cost = 6;
protected int getCost() {
return cost;
}
}
但是如果我想實現這個我會做的就是讓 CoffeeMachine 像這樣抽象
abstract class CoffeeMachine {
private int cost;
CoffeeMachine(int cost) {
this.cost = cost;
}
int getCost() {
return cost;
}
}
然后像這樣在我的超類上擴展它
class FancyCoffeeMachine extends CoffeeMachine {
FancyCoffeeMachine(int cost) {
super(cost);
}
}
并這樣稱呼它
FancyCoffeeMachine fancyCoffeeMachine = new FancyCoffeeMachine(6);
System.out.println(fancyCoffeeMachine.getCost());

TA貢獻1812條經驗 獲得超5個贊
您通常不會像cost在子類中那樣重新定義受保護的字段。相反,您將在構造對象時為子類提供一種設置成本的方法??催@個:
public class Scratch {
public static class CoffeeMachine {
protected int cost;
public CoffeeMachine() {
this(3);
}
protected CoffeeMachine(int aCost) {
cost = aCost;
}
public int getCost() {
return cost;
}
}
public static class FancyCoffeeMachine extends CoffeeMachine{
public FancyCoffeeMachine() {
super(6);
}
}
public static void main(String[] args) {
System.out.printf("plain: %d\n", new CoffeeMachine().getCost());
System.out.printf("fancy: %d\n", new FancyCoffeeMachine().getCost());
}
}
(不用擔心這兩個CoffeeMachine類被聲明為靜態的。這只是為了讓它們都可以在一個文件中定義。)
基類CoffeeMachine有兩個構造函數:
接受成本作為參數的受保護構造函數。
將成本設置為 3 的公共構造函數。
子FancyCoffeeMachine類以 6 的成本調用受保護的超類構造函數。因此該cost變量設置為 6,并getCost()在您運行它時返回該值:
plain: 3
fancy: 6
添加回答
舉報