Can non-static methods modify static variables

2019-01-07 09:22发布

问题:

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.

回答1:

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



回答2:

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.



回答3:

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



回答4:

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.



回答5:

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.



回答6:

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.



回答7:

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



回答8:

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();

    }
}


回答9:

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);
   }
}