Should a java class' final fields always be static?

后端 未结 8 895
你的背包
你的背包 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 23:03

    Of course not. They must be static if they belong to the class, and not be static if they belong to the instance of the class:

    public class ImmutablePerson {
        private static final int MAX_LAST_NAME_LENGTH = 255; // belongs to the type
        private final String firstName; // belongs to the instance
        private final String lastName; // belongs to the instance
    
        public ImmutablePerson(String firstName, String lastName) {
            if (lastName.length() > MAX_LAST_NAME_LENGTH) {
                throw new IllegalArgumentException("last name too large");
            }
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        // getters omitted for brevity
    }
    

提交回复
热议问题