I am wondering how a non static method can modify a static instance variable. I know that static methods can only access other static methods and static variables. However, is the other side true? Can non-static methods access only non-static variables? For example:
public class SampleClass {
private static int currentCount = 0;
public SampleClass() {
currentCount++;
}
public void increaseCount() {
currentCount++;
}
}
This code compiles and I would like to know why in terms of static access privledges.
Non static methods can access static variables. Static methods can access only static variables or methods directly without creating object.ex:public static void main(String arg[])
Static members are not instance members , these are shared by class , so basically any instance method can access these static members .
Non-Static Methods can access both Static Variables & Static Methods as they Members of Class
Demo Code
Yes, a static method can access a non-static variable. This is done by creating an object to the class and accessing the variable through the object. In the below example
main
is a static method which accesses variablea
which is a non-static variable.demo code:
I have found this from The Java Tutorials
So the answer is yes, non-static methods CAN modify static variables
Look at it this way. A static variable can be accessed in many ways. One of the most common is to precede the var name with the class name, since static vars are per class. Since you refer to this variable in the same class, you are exempt from having to precede it with the class name. It does not matter where you call the static variable. Also this is a private static var not accessible by any other class.