In Java, why can't I declare a final member (w/o initializing it) in the parent class and set its value in the subclass? How can I work around?

前端 未结 8 1259
长情又很酷
长情又很酷 2020-12-07 01:29

In a Java program, I have multiple subclasses inheriting from a parent (which is abstract). I wanted to express that every child should have a member that is set once only (

8条回答
  •  悲&欢浪女
    2020-12-07 01:57

    You can't do it because while comparing the parent class, the compiler can't be sure that the subclass will initialize it. You'll have to initialize it in the parent's constructor, and have the child call the parent's constructor:

    public abstract class Parent {
        protected final String birthmark;
        protected Parent(String s) {
            birthmark = s;
        }
    }
    
    public class Child extends Parent {
        public Child(String s) {
            super(s);
            ...
        }
    }
    

提交回复
热议问题