Static methods cant access instance fields?

后端 未结 1 426
轮回少年
轮回少年 2021-01-27 12:13

I have read many article regarding the static fields that**\"Static methods have no way of accessing fields that are instance fields, as instance fields only exist on instances

1条回答
  •  走了就别回头了
    2021-01-27 12:28

    You cannot access instance fields of the class that the static method is part of, because a static method is not called on an instance of this class. If you create an instance of that class, you can access it's instance fields as normal.

    Your b is not an instance field, it's a normal local variable.

    The sentence you quoted just means that you cannot do what you tried in the line you commented out: you cannot access a without an instance. Non-static methods use this as the default instance, so you could access a by simply writing a = 17; which is equivalent to this.a = 17;

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