Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need to implement in another class

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading