static vs non static

后端 未结 4 1816
梦谈多话
梦谈多话 2020-12-19 04:21

Until few weeks back, I thought I understand when to make fields and methods static or non-static. For example, when a field (say object of another

4条回答
  •  感动是毒
    2020-12-19 04:30

    It might be thin but there is very clear distinction. You declare a field as static when it is not at all related to any instance of a class.

    A simple usecase of static field is declaring constants using final keyword, e.g.:

    public static final int MAX_ALLOWED = 10;
    

    Same is the case with methods also. You declare a method as static when it is not dependent on instance of a class OR the state of the class. That's the reason a static method cannot use instance members of a class.

提交回复
热议问题