Should a java class' final fields always be static?

后端 未结 8 943
你的背包
你的背包 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:55

    Absolutely not. Consider:

    class Point {
        public final int x;
        public final int y;
    
        public Point(int _x, int _y) {
            x = _x;
            y = _y;
        }
    }
    

    Drop the final, and the class becomes mutable. Add a static, and all your points are the same, and there is no legal way to write the constructor.

提交回复
热议问题