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

懵懂的女人 提交于 2020-01-22 03:44:05

问题


I have a class with some variables. When I instantiate an object of that class in the main class. I can only access and modify member variables in a method, any method; not outside them. Why is that? I am stuck and can't seem to find an answer on 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){
    }
}

Also I tried access specifiers and got the same result


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/53675473/why-cant-i-modify-class-member-variable-outside-any-methods

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