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:
- They could be accessed with Object reference variable or ClassName using dot operator or directly if accessing in from same class.
- 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.