如何在java中访问对象的静态变量? [英] how do you access a static variable of an object in java?

查看:215
本文介绍了如何在java中访问对象的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序,我必须包含两个静态变量。在创建十个对象的数组之前,我将它们包含在我的构造函数中。以后,我试图通过以下方式实现一个静态变量:

  if(finalScore> = students.get (0).minA){
finalLetterGrade =A;
aCounter ++;
//(student.get(0).minA = 90)

程序应该工作正常,但是Ecipse不允许我保存程序,因为出现以下错误信息:
静态字段ClassGrade.minA应以
静态方式访问
错误在我提供的代码的第一行弹出。任何人都可以向我解释一下正确的方法,以便在java中访问一个对象的静态变量,或者至少建议我如何解决这个错误消息并保存我的程序?

解决方案

您得到警告,因为 static 方法应通过其容器类本身访问( Classname.staticMethod()),而不是其中一个实例。如果(finalScore> = students.get(0).minA)

to

  if(finalScore> = ClassGrade.minA)


I am working on a program where i have to include two static variables. I included them in my constructor before creating an array of ten objects. Later on, I tried to implement one of the static variables in the following way:

if (finalScore >= students.get(0).minA){
            finalLetterGrade = "A";
            aCounter++;
//(student.get(0).minA = 90)

The program shouldve worked fine, however Ecipse isn't allowing me to save the program because of the following error message: "The static field ClassGrade.minA should be accessed in a static way" The error pops up at the first line of the code that i provided. Could anyone explain to me the correct way to supposedly access a static variable of an object in java, or at the very least advise me on how to get past this error message and save\run my program?

解决方案

You get the warning because static methods should be accessed via their container class itself (Classname.staticMethod()), not by one of its instances. Change

if (finalScore >= students.get(0).minA)

to

if (finalScore >= ClassGrade.minA)

这篇关于如何在java中访问对象的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆