java - 需要在另一个类中实现
问题描述
我有这堂课:
public class ShoppingList {
public int calculateTotal(){
int sum = 0;
for(Item item : items){
sum += item.getPrice();
}
return sum;
}
}
现在,我需要在另一个类中做这样的事情:
if (calculateTotal > 25) {
--some stuff--
}
如何正确引用这个CalculateTotal?
解决方案
你有两个选择:
- 实例化您的类并将该方法与新对象一起使用
ShoppingList myShoppingList = new ShopingList();
if(myShopingList.calculateTotal() > 25){
// some stuff
}
- 使您的
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
}
推荐阅读
- python - 找不到 pyinstaller 命令
- javascript - 无法从 Javascript 中的输入类型数字标签中获取输入的数字
- javascript - vue-electron:如何在 prod 模式下关闭/最小化窗口
- javascript - 是否可以在 firestore 中获取第 n 个文档,或者在添加后为每个 firestore 文档分配一个编号?
- scala - 将转换应用于 Spark Scala 中的列
- api - 如何使用图形 API 获取具有特定 github 主题的所有存储库
- vue.js - 如何在 vuejs 中将上一页 url 存储为字符串?
- java - 如何从本地主机连接到 docker redis 集群
- wagtail - 如何修复由 wagtail 中的 routeablepage 产生的 FieldError
- r - R:循环遍历列表并向数据框添加值