-2

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?

stonar96
  • 1,359
  • 2
  • 11
  • 39

2 Answers2

7

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);
    }
}
user902383
  • 8,420
  • 8
  • 43
  • 63
  • 2
    I am talking about the constructor. – stonar96 Aug 24 '16 at 23:26
  • @stonar96 you set value of `b` when you called constructor of super class. If you want to set it to different value in subclass, you need to pass that value to super class constructor. – user902383 Aug 24 '16 at 23:30
1

It can't be done because the definition of a final field is that it can only be assigned once. If A() assigned the protected field already, assigning it again in B() still violates "only once", even if it's done in the constructor.

CodeBlind
  • 4,519
  • 1
  • 24
  • 36