Home > Blockchain >  Need to implement in another class
Need to implement in another class

Time:11-15

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:

  1. Instantiate your class and use the method with the new object
    ShoppingList myShoppingList = new ShopingList();
    if(myShopingList.calculateTotal() > 25){
        // some stuff
    }
  1. 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
}
  • Related