Search code examples
javaoopinheritancesubclasssuperclass

Create a final field initialized by a child class


I have an abstract class with subclasses that share a method that increments a value by a specific increment and is bounded by a lower limit and an upper limit. Each subclass has its own increment and its own bounds These values should all be declared final, but if I declare them final how can they be initialized by the subclasses.

Below is the only way I could think of to get it to work, but it seems rather cumbersome.

public abstract class ClassA {
    protected int LOWER_LIMIT;
    protected int UPPER_LIMIT;
    protected int INCREMENT;

    public ClassA() {
    }
}

public class ClassB extends ClassA {
    public ClassB() {
        super();
        this.LOWER_LIMIT = 0;
        this.UPPER_LIMIT = 4200;
        this.INCREMENT = 15;
    }
}

public class ClassC extends ClassA {
    public ClassC() {
        super();
        this.LOWER_LIMIT = 0;
        this.UPPER_LIMIT = 99;
        this.INCREMENT = 1;
    }
}


Solution

  • The quite common pattern is this. You also force the subclasses to define the value.

    public abstract class Base {
        final protected int field1;
        final protected int field2;
        final protected int field3;
    
        protected Base(int field1, int field2, int field3) {
            this.field1 = field1;
            this.field2 = field2;
            this.field3 = field3;
        }
    
    }
    
    public class Subclass extends Base {
        public Subclass () {
            super(0, 4200, 15);
        }
    }