Should a java class' final fields always be static?

后端 未结 8 971
你的背包
你的背包 2021-01-03 22:36

I could not find any references online about this. But just wanted to know if final fields in a class should always be static or is it just a convention. Based

8条回答
  •  忘掉有多难
    2021-01-03 22:39

    Final fields do not need to be static, and sometimes it can be useful to have a non-static final instance variable. Fields that are marked both static and final are usually used for constants, like this:

    public static final int BORDER_WIDTH = 5;
    

    However, sometimes you'll see a non-static final field when an object has a immutable property. Usually, non-static final fields are still marked private for the usual reasons, though, so it's more of an extra check so the compiler can make sure you're never setting the property again.

提交回复
热议问题