我有一类带有一些变量的类。当我在主类中实例化该类的对象时。我只能访问和修改一个方法(任何方法)中的成员变量;不在他们外面。这是为什么?我被困住了,似乎无法在Google上找到答案。
class SomeVariables{ String s; int dontneed; } class MainClass{ SomeVariables vars= new SomeVariables(); vars.s = "why this doesnt work?. IDE says Uknown class 'vars.s'"; System.out.println(vars.s); // Accesing it also doesnt work void ChangeValue(){ vars.s = "why does this work?"; } public static void main(String[]args){ } }
我也尝试访问说明符并得到相同的结果
它不起作用,因为您是在无效的Java语法的构造函数或方法之外定义实例的。
可能的解决办法是:
class SomeVariables { String s; int dontneed; } class MainClass { public static void main(String[]args){ SomeVariables vars = new SomeVariables(); vars.s = "why this doesnt work?. IDE says Uknown class 'vars.s'"; System.out.println(vars.s); } }
但是您可能要考虑保护您的类变量,例如使所有属性成为SomeVariables并使用setters和getters方法来获取和修改类本身中的值。例如:
SomeVariables
setters
getters
class SomeVariables { private String s; private int dontneed; // Constructor method public SomeVariables() { // Initialize your attributes } public String getValue() { return s; } public void setValue(String value) { s = value; } } class MainClass { public static void main(String[]args){ SomeVariables vars = new SomeVariables(); vars.setValue("Some value"); System.out.println(vars.getValue()); } }