2 回答

TA貢獻1963條經(jīng)驗 獲得超6個贊
通過稍后簡單地讀回這些字段,可能是直接讀取,或者使用您添加的 getter 方法,例如:
if (someFruit.getName().equals(theNameOfSomeFoodOrderedByCustomer)) {
System.out.println("you ordered " + someFruit.getName() + " that will cost you " + someFruit.getPrice());
從那時起,您可能想要更多地研究 java getter/setter 方法,以查看相關(guān)示例。

TA貢獻1862條經(jīng)驗 獲得超6個贊
要訪問您的對象之一的非私有成員變量,請使用該.符號,如下所示:
Fruit apple = new Fruit("Apple", "Apple", "0.45", 23);
System.out.println(apple.price); //prints the price of the apple
但是,在大多數(shù)情況下,為了封裝,建議您使用 getter 和 setter 方法。這樣,您可以更好地控制對象變量的訪問方式??纯聪旅娴睦樱?/p>
private int price; //a private member variable
//...
public int getPrice() {return this.price} //example of a getter method
public void setPrice(int nPrice) {this.price = nPrice;} //example of a setter method
在上面的示例中,您將無法price直接在其類之外訪問該變量。相反,您必須getPrice()從Fruit.
注意:最好以小寫字母開頭變量名。
添加回答
舉報