【问题标题】:Need to implement in another class需要在另一个类中实现
【发布时间】:2021-12-25 23:34:24
【问题描述】:

我有这门课:

public class ShoppingList {

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

}

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

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

如何正确引用这个CalculateTotal?

【问题讨论】:

  • 1.实例化一个ShoppingList 对象(或将一个作为参数传入)- 2. 调用calculateTotal 就可以了。 - 3. 利润

标签: java class reference


【解决方案1】:

你有两个选择:

  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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多