为什么我不能在任何方法之外修改 class 成员变量?

Why can't I modify class member variable outside any methods?

我有一个带有一些变量的 class。当我在主 class 中实例化那个 class 的对象时。我只能在一个方法中访问和修改成员变量,任何方法;不在他们之外。这是为什么?我被卡住了,似乎无法在 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){
    }
}

我也尝试了访问说明符并得到了相同的结果

这里是一个超级简化的答案,如果您需要更多详细信息,请添加评论 ;)

class SomeVariables{
    String s;
    int dontneed;
}
class MainClass{
    // this is ok
    SomeVariables vars= new SomeVariables();
    // not allowed here, must be on method, main for example
    vars.s = "why this doesnt work?. IDE says Uknown class 'vars.s'";
    // not allowed here, must be on method, main for example
    System.out.println(vars.s);        // Accesing it also doesnt work

    void ChangeValue(){
        // it works because is on scope and inside a method
        vars.s = "why does this work?";
    }

    public static void main(String[]args){
        // here sholud be your statements var.s = ... and System.out.println
    }
}

它不起作用,因为您在无效的 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);
    }
}

但您可能需要考虑保护您的 class 变量,例如将所有属性设为 SomeVariables 并使用 settersgetters 方法来获取和修改class 本身的值。例如:

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());
    }
}