我有這門課:
public class ShoppingList {
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum = item.getPrice();
}
return sum;
}
}
現在,我需要在另一個類中做這樣的事情:
if (calculateTotal > 25) {
--some stuff--
}
如何正確參考此CalculateTotal?
uj5u.com熱心網友回復:
您有兩個選擇:
- 實體化您的類并將該方法與新物件一起使用
ShoppingList myShoppingList = new ShopingList();
if(myShopingList.calculateTotal() > 25){
// some stuff
}
- 使您的
calculateTotal方法靜態并在不需要實體的情況下使用它。
public class ShoppingList {
public static int calculateTotal(){
int sum = 0;
for(Item item : items){
sum = item.getPrice();
}
return sum;
}
}
進而
if(ShoppingList.calculateTotal() > 25){
// some stuff
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/357438.html
上一篇:一起定義fmt::Display和fmt::Debug
下一篇:哈希集迭代器列印
