Should a private final field be static too?

前端 未结 5 1099
孤独总比滥情好
孤独总比滥情好 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:15

    There is a big difference between the two non-access modifiers.

    • final means your variable can be assigned a value once.
    • static sets its scope to pertain to the class (rather than an instance or a local context).

    There is no reason why they should go together unless by design.

    A static final variable is de facto a constant.

    For instance, fields declared in interfaces are implicitly public, static and final.

    Amongst the usage examples for final, non static fields you can find:

    • fields declared outside an anonymous class and being referenced inside it
    • local fields (declared in a method's body) being referenced inside a local class (declared in the same method's body)
    • etc...

提交回复
热议问题