Should a private final field be static too?

前端 未结 5 1129
孤独总比滥情好
孤独总比滥情好 2020-12-21 21:48

I was wondering, if I have this field in my class : private final int foo = ..., should I put it in static private static final int foo = ...? Beca

5条回答
  •  天命终不由人
    2020-12-21 22:23

    It is a constant and you will not want to have one copy of the variable for each instance of the class,so make it static. Also, if you want to use them from a static method, make it static.

    Static variables are those variables which are common for all the instances of a class.If one instance changes it, then value of static variable would be updated for all other instances.

    If you do not want this behavior, keep it non-static.

提交回复
热议问题