27

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.

Community
  • 1
  • 1
Brian
  • 7,098
  • 15
  • 56
  • 73
  • 7
    did you try it? – Marco Forberg Jun 21 '13 at 19:12
  • 3
    @Marco Yes, it compiles. Just wondering if people have documented this anywhere, and whether my reasoning is correct. – Brian Jun 21 '13 at 19:16
  • 2
    It's not really true that static methods cannot modify instance variables. It's just that they don't have any implicit "this" references. You can write `class Ex { private int x; static void fn(Ex ex) { ex.x = 12; } }`. BTW: Mutable statics are generally a bad idea. – Tom Hawtin - tackline Jun 21 '13 at 19:21
  • 1
    Answer to question: yes they can; no, don't do that. – fge Jun 21 '13 at 19:49

9 Answers9

45

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

Brian
  • 7,098
  • 15
  • 56
  • 73
17

No, any non-static method has access to static members. The only way this would be false is if the non-static context did not have access to the static member (ex. the static member is private to a class and the non-static code is not in that class). static variables exist to provide an instance free variable/method, so for example if we have a Game class and a highscore variable, the highscore would be static (accessible without an instance), and after every game (an instance of the Game class) completes we could alter the highscore from our non-static context if our score is greater than the high score.

Robert Mitchell
  • 892
  • 7
  • 9
6

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[])

vaishnavi
  • 69
  • 1
  • 1
1

Non-Static Methods can access both Static Variables & Static Methods as they Members of Class

Demo Code

public class Static_Class {
    protected static String str;
    private static int runningLoop;

    static{
        str = "Static Block";
    }

    /**
     * Non-Static Method Accessing Static Member  
     */
    public void modifyStaticMember(){
        str = "Non-Static Method";      
    }

    /**
     * Non-Static Method invoking Static Method
     */
    public void invokeStaticMethod(){
        String[] args = {};
        if(runningLoop == 0){
            runningLoop++;
            main(args); 
        }
        //Exiting as it will lead to java.lang.StackOverflowError
        System.exit(0);
    }

    public static void main(String[] args) {
        Static_Class instance = new Static_Class();
        System.out.println(str);
        instance.modifyStaticMember();

        // Changed Value persists 
        System.out.println(str);

        //Invoking Static Method
        instance.invokeStaticMethod();

    }
}
Abhijeet
  • 8,561
  • 5
  • 70
  • 76
0

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.

happybuddha
  • 1,271
  • 2
  • 20
  • 40
0

Static methods cannot modify Non-static fields since - For using a Non-Static field (outside the class) you must instantiate a class object, But for using a Static method there is no need for object instantiation at all. This is why it's not reasonable for a Non-Static Method (which not demands an object instantiation) to modify a field that should be instantiated.

For this - Static methods can touch only static fields (or call other static methods).

But as you mentioned the other way around is possible, A Non-Static method can modify a static field which is static for all objects of its class.

Mercury
  • 7,430
  • 3
  • 42
  • 54
  • What if we have a static instance of that class?....we can then use that static object to modify the non static fields. Am i correct in this? – BharatProteemGogoi Sep 23 '18 at 14:08
0

Static variables are class variable not instance or local variable . that is why we can use static variable in non static method also. and static variables are not per object . static variables have one copy that will be used in entire program.

Abhishek
  • 379
  • 1
  • 8
0

Static members are not instance members , these are shared by class , so basically any instance method can access these static members .

hellrocker
  • 628
  • 8
  • 15
-1

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 variable a which is a non-static variable.

demo code:

public class Sample {

   private int a;

   void method()
   {
       System.out.println("i am a private method");
   }

   public static void main(String[] args)
   { 
       Sample sample=new Sample();
       sample.a=10;
       System.out.println(sample.a);
   }
}   
Michael Albers
  • 3,721
  • 3
  • 21
  • 32
  • The question is probably looking the other way round. Accessing static variable from non-static method. – Pramod Setlur Sep 19 '19 at 23:31
  • Sorry, but I think your statement "Yes, a static method can access a non-static variable" is incorrect. In your example, your "main" function is NOT a method of a class, generally speaking, and that "main" function is a special function with "main" as a keyword. Many experts have said 2 things: (1) Static methods cannot access or modify non-static data members of a class. And static-methods can only access or modify static data members of a class. (2) Non-static methods can modify both static and non-static data members of a class. – Job_September_2020 Nov 28 '20 at 03:36