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

*爱你&永不变心* 提交于 2019-12-02 07:56:36

It does not work because you are defining the instances outside of a constructor or methos which is not valid Java syntax.

A possible fix would be:

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

But you might want to consider protection of your class variables such are making all attributes og the SomeVariables and use setters and getters methods to get and modify the value in the class itself. For example:

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

here is a super simplified answer, if you want more details just add a comment ;)

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
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!