首页 > 解决方案 > 需要在另一个类中实现

问题描述

我有这堂课:

public class ShoppingList {

    public int calculateTotal(){
        int sum = 0;
        for(Item item : items){
            sum += item.getPrice();
        }
        return sum;
    }

}

现在,我需要在另一个类中做这样的事情:

if (calculateTotal > 25) {
      --some stuff--
}

如何正确引用这个CalculateTotal?

标签: javaclassreference

解决方案


你有两个选择:

  1. 实例化您的类并将该方法与新对象一起使用
    ShoppingList myShoppingList = new ShopingList();
    if(myShopingList.calculateTotal() > 25){
        // some stuff
    }
  1. 使您的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
}

推荐阅读