Search code examples
javamember

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


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


Solution

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