Can non-static methods modify static variables

Brian picture Brian · Jun 21, 2013 · Viewed 87.6k times · Source

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.

Answer

Brian picture Brian · Mar 4, 2014

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