Can non-static methods modify static variables

前端 未结 9 2129
猫巷女王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: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.

提交回复
热议问题