2016-07-17 31 views
1

可以說我正在構建一個FoodItem,並且我想輸入一個新項目,我想確保該項目的名稱不能改變,它的價格也是如此(意味着我不能使用Setter來改變它),但是我將能夠改變數量。如何將輸入(int,String等)轉換爲相同類型的最終變量?

我的問題如下所示:通過在構造函數中聲明結尾NAME和COST,我無法訪問它們,例如getName()或getCost()方法。 我希望我的問題很清楚,如果不是隻是問,我會回覆。

我還是一個java初學者,所以原諒我,如果我失去了一些明顯的東西,我在這裏學習!

public class FoodItem { 

    private int _quantity; 

    public FoodItem (String name, int cost, int quantity){ // 
     final String NAME = name; 
     final int COST = cost; 
     _quantity = quantity; 
    } 

    public String getName(){ return NAME;} //<-- obviously cannot be found 
    public int getCost(){ return _cost;} 
    public int getNumber(){ return NUMBER;} 
    public void setCost(int newCost){ _cost = newCost;} 

回答

3

NAME和COST被聲明在錯誤的地方。在聲明_quantity的地方移動他們的聲明。

private int _quantity; 
private final String NAME; 
private final int COST; 

public FoodItem (String name, int cost, int quantity){ 
    NAME = name; 
    COST = cost; 
    _quantity = quantity; 
} 

查看答案here

+0

感謝您的快速回復,我沒有嘗試在開始時聲明它們,因爲我認爲我無法更改它們(或爲它們分配值)。你能幫我理解爲什麼這是不同的,然後使用Setter(不起作用)。是否因爲只有在收到價值後才設定爲最終?或者它是在構造函數中創建的事實? – Immanuel

+1

決賽只能在構造函數創建對象時設置。 – zeb

+0

非常感謝! – Immanuel

1

要回答你的問題,首先,你應該知道的信息隱藏概念

您可以隱藏不給訪問的數據(指沒有接入方式私人範圍)

所以在這個例子中,你可以作爲寫下面

public class FoodItem { 

    private int quantity; 
    private String name; 
    private int cost; 

    public FoodItem (String name, int cost, int quantity){ // 
     this.name = name; 
     this.cost = cost; 
     this.quantity = quantity; 
    } 

    public String getName(){ return name;} 
    public int getCost(){ return cost;} 
    public int getQuantity(){ return quantity;} 
    // providing a setter so that some one can change the quantity 
    public void setQuantity(int quantity){ this.quantity = quantity;} 

} 

在上面的例子我還沒有爲name提供setter和cost所以沒有一個可以訪問它們,沒有人可以改變它們的值(它們被創建時除外)以及用於全因爲你提到它可以修改,所以這就是爲什麼我提供了setter,所以如果有人想改變數量,然後可以打電話給obj.setQuantity(<new quantity>);方法

希望你有這個概念。

+0

這與OP要求的無關 – Yar

+0

感謝您的評論,但Yar是正確的,我正在具體詢問「最終」聲明。 – Immanuel

+0

我同意你的看法Immanuel,我不知道這個,因爲我曾經聲明最終變量總是靜態的。但學到了新東西。謝謝亞爾。 –

相關問題