1

I was trying to understand how static data-members of class behave in java. As Static Members are not part of any Instances rather they are shared for all Instances of same class. What I came up with is:

  1. They could be accessed with Object reference variable or ClassName using dot operator or directly if accessing in from same class.
  2. Keeping (1) in mind they could be accessed from methods no matter if method is static or non-static.

Question: Why could they be accessed with object reference variables as it's not allowed in some languages like C#, C++ etc, and why could they be accessed from non-static methods ? Isn't it redundant or contrary with concept of Static Data-Members ?

Following is my code that bugged my mind to ask this question.

pubic class ClassWithStaticMember{
    public static int _variable;   

    static{
       _variable = 2;      // Default Value will be 2
    }

    public static void modifyVariable(){    // Static Method that Modifies _variable
        _variable = 3
    }

    public void NSmodifyVariable)(){       // Non-Static Method that Modifies _variable
        _variable = 6;
    }

    public static void printVariable(){     // Static Method that prints _variable
        System.out.println("Static Data-Member _variable: " + _variable);
    }
}

public class MainClass {
    public static void main (String[] args){
        ClassWithStaticMember.printVariable();   //Prints _variable = 2 that was initialized in static block

        ClassWithStaticMember._variable = 9;     
        ClassWithStaticMember.printVariable();   //Prints _variable = 9

        ClassWithStaticMember.modifyVariable();
        ClassWithStaticMember.printVariable();   //Prints _variable = 3

        ClassWithStaticMembers _Instance = new ClassWithStaticMember();
        _Instance._variable = 4;    // Changes _variable to 4
        _Instance.printVariable();               //Prints _variable = 4

        _Instance.NSmodifyVariable();
        _Instance.printVariable();               //Prints _variable = 6
    }
}

I expect not to access static members "in non-static methods" and "through Object Reference Variable" but java allows to do so.

  • 3
    *Why could they be accessed with object reference variables as it's not allowed in some languages like C#, C++ etc*: because Java is not C# or C++, and its designers chose different rules for the language.* Isn't it redundant or contrary with concept of Static Data-Members?* It's indeed considered a design mistake generally. Accessing the variable without prepending the class inside the class itself is basically OK, but using `someObject.staticMember` instead of `SomeClass.staticMember` is bad practice. – JB Nizet May 01 '19 at 13:06
  • 1
    https://stackoverflow.com/questions/4978000/static-method-in-java-can-be-accessed-using-object-ins | https://stackoverflow.com/questions/7884004/is-calling-static-methods-via-an-object-bad-form-why – Slaw May 01 '19 at 13:09

0 Answers0