Can non-static methods modify static variables

前端 未结 9 2010
猫巷女王i
猫巷女王i 2020-11-29 01:53

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 ot

相关标签:
9条回答
  • 2020-11-29 02:15

    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.

    0 讨论(0)
  • 2020-11-29 02:18

    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.

    0 讨论(0)
  • 2020-11-29 02:23

    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.

    0 讨论(0)
提交回复
热议问题