Should a private final field be static too?

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

    if you initiate its value in the constructor then it should not be static like

    private final int foo;
    
    public MyClass(int m){
        foo=m;
    }
    

    because its value depends on entry value.


    but if you initiate its value inline like

    private final int foo = 100;
    

    then its preferred to be static to have just one instance of it, since the final field will be created on each instance of class; but static will be created once.

提交回复
热议问题