Search code examples
javaconstructorsubclassfinalprotected

Java Why isn't it allowed to set a protected final field from a subclass constructor?


Why isn't it allowed to set a protected final field from a subclass constructor?

Example:

class A {
    protected final boolean b;

    protected A() {
        b = false;
    }
}

class B extends A {
    public B() {
        super();
        b = true;
    }
}

I think it would make sense in some cases, wouldn't it?


Solution

  • It's because you can't change value of final fields.

    But if you really want to se it to different value, you could do:

    class A {
        protected final boolean b;
    
        protected A() {
        this(false);
        }
        protected A(boolean b) {
           this. b = b;
        }
    }
    
    class B extends A {
        public B() {
            super(true);
        }
    }