Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can non-static methods modify static variables

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.

like image 623
Brian Avatar asked Jun 21 '13 19:06

Brian


People also ask

Can non-static method change static variable?

“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.

Can static methods modify static variables?

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.

Can non-static method access static fields?

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.

Can static variables be changed?

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.


1 Answers

I have found this from The Java Tutorials

  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

So the answer is yes, non-static methods CAN modify static variables

like image 58
Brian Avatar answered Oct 07 '22 16:10

Brian