Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading