I have this class:
public class ShoppingList {
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum = item.getPrice();
}
return sum;
}
}
Now, I need to make something like this in another class:
if (calculateTotal > 25) {
--some stuff--
}
How to reference this CalculateTotal correctly?
CodePudding user response:
You have two options:
- Instantiate your class and use the method with the new object
ShoppingList myShoppingList = new ShopingList();
if(myShopingList.calculateTotal() > 25){
// some stuff
}
- Make your
calculateTotal
method static and use it without the need of the instance.
public class ShoppingList {
public static int calculateTotal(){
int sum = 0;
for(Item item : items){
sum = item.getPrice();
}
return sum;
}
}
And then
if(ShoppingList.calculateTotal() > 25){
// some stuff
}