了解Java实例和静态关键字
我可以做什么来使用 Program 类上的 getTotalScore
方法来获取我的 scores ArrayList
的总和,为什么我必须这样做?我想明白。请注意,我不想使该方法静态。
import java.util.*;
public class Program {
public int getTotalScore(ArrayList<int> v) {
return total;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<int> scores = new ArrayList<>();
}
}
我找不到一篇文章可以帮助我清楚地了解发生了什么,请帮忙。我在某处收到这样的评论:
请注意,scores 对象不是静态的,因此您必须创建一个实例
Program
类,以便使用分数ArrayList
和getTotalScore
方法。
what can I do to use the getTotalScore
method on the Program class to get the total of my scores ArrayList
, and why must I do that? I wanna understand. Please note I don't wanna make the method static.
import java.util.*;
public class Program {
public int getTotalScore(ArrayList<int> v) {
return total;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<int> scores = new ArrayList<>();
}
}
I can't find an article to help me understand clearly what is up, please help. I got this comment somewhere:
Note that the scores object is not static, so you will have to make an instance of the
Program
class in order to use the scoresArrayList
and thegetTotalScore
method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果要使用类的非静态成员,则必须实例化该类。所以在这种情况下
,创建
Program
类的实例是非常奇怪的。将方法getTotalScore
移至新类(或使其静态)。为了计算总数,请查看如何对整数数组进行“求和”。
If you want to use a non-static member of a class, you must instantiate the class. So in this case
This is very weird, to create an instance of the
Program
class. Move the methodgetTotalScore
to a new class instead (or make it static).For calculating the total, look up how to “sum” an array of integers.
静态
成员属于类,而不是实例。为了使用
getTotalsCore
MAIN 方法中的方法,您要么必须创建一个program> program>的对象,要么制作<代码> getTotalsCore
静态方法。以下是两个示例:
program的实例
getTotalsCore
静态方法static
members belong to a class, not an instance.In order to use
getTotalScore
method inside yourmain
method, you'll either have to create an object that is instance ofProgram
, or makegetTotalScore
a static method.Here are two examples:
Program
getTotalScore
a static method这里
我包括两种类型的 instatiate 对象(在本例中是调用方法)。
}
Here I have include two type of instatiate object(in this case calling method).