setPrice()是一种方法。您似乎也有一个名为 的方法getPrice(),这些方法可能都对应price于您的对象中调用的实例变量。
如果price是private,那么你getPrice()这样调用:
wineCase1.getPrice();
这将返回一个double(假设price是 double 类型)。
同样,如果priceis private,那么您需要将其设置为:
wineCase1.setPrice(somePrice);
所以在你上面的例子中,如果你想设置price为当前的 90%,正确的语法应该是这样的:
wineCase1.setPrice(0.9*wineCase1.getPrice());
或者,您可能会public为此类编写一个方法,如下所示:
public void discountBy(double disc) {
price *= 1.0 - disc;
}
// or like this:
public void discountTo(double disc) {
price *= disc;
}
// or both...
要使用此方法并对 应用 10% 的折扣wineCase1,您可以执行以下操作:
wineCase1.discountBy(0.1);
// or like this:
wineCase1.discountTo(0.9);
然后你仍然会使用:
wineCase1.getPrice();
从对象中检索私有变量 , price。
最后,这可能是最好的解决方案,添加这些方法:
public double getPriceDiscountedBy(double disc) {
return price*(1.0-disc);
}
public double getPriceDiscountedTo(double disc) {
return price*disc;
}
这些方法将允许您在不更改商品原始价格的情况下检索折扣价的价值。这些将在您获得 a 的相同位置调用getPrice,但使用折扣参数仅修改返回的价格。例如:
double discountedPriceOutsideOfObject = wineCase1.getPriceDiscountedTo(0.9);
//or like this:
double discountedPriceOutsideOfObject = wineCase1.getPriceDiscountedBy(0.1);