Should a java class' final fields always be static?

后端 未结 8 940
你的背包
你的背包 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条回答
  •  Happy的楠姐
    2021-01-03 22:55

    They don't always come together and it's not a convention. final fields are often used to create immutable types:

    class Person {
    
        private final String name;
        private final int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public int getAge() {
            return age;
        }
    
    }
    

    On the other hand static but not final fields are not that common and are quite tricky. static final is seen often because it means application1-wide constant.

    1 - well, class loader-wide, to be precise

提交回复
热议问题