I am wondering how a non static method can modify a static 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.
“Can a non-static method access a static variable or call a static method” is one of the frequently asked questions on static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java.
Static methods only have access to other static variables and static methods. Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods.
non-static methods can access any static method and static variable also, without using the object of the class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
A static variable is common for all instances of the class. A final variable can not change after it has been set the first time. So a static final variable in Java is common for all instances of the class, and it can not be changed after it has been set the first time.
I have found this from The Java Tutorials
So the answer is yes, non-static methods CAN modify static variables
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With