Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Setting Class Properties Before Super [duplicate]

Tags:

I have the follow classes:

public abstract class MyAbstractClass {
     protected int x;
     protected int number;
     public MyAbstractClass(int x) {
         this.x = x;
         this.number = this.generateNumber();
     }
     public abstract int generateNumber(); // This class is called in the super constructor and elsewhere
}
public class MySubClass extends MyAbstractClass {
     private int y;
     public MySubClass(int x, int y) {
          super(x);
          this.y = y;
     }
     @Override
     public int generateNumber() {
         return this.x + this.y; // this.y has not been initialized!
     }
}

My issue is that MySubClass's y property has to be initialized before the super constructor is run, because a method using y is run in the super constructor. I am aware that this may not be possible even with some sneaky workaround, but I am yet to find an alternative solution.

Also please keep in mind that I will have many more derived classes, with different values being passed into their constructors.

like image 819
klo Avatar asked Sep 29 '20 05:09

klo


1 Answers

You can defer the number calculation until it is needed.

public abstract class MyAbstractClass {
    protected int x;
    protected Integer number;

    public MyAbstractClass(int x) {
        this.x = x;
    }

    public int getNumber() {
        if (number == null) {
            number = generateNumber();
        }
        return number.intValue();
    }

    protected abstract int generateNumber(); 
}
like image 151
René Link Avatar answered Oct 02 '22 16:10

René Link