Java - how to call different super() according to inheriting class's constructor argument?

inheritance, java, super

Solution

If finding the other arguments is a complex operation (i.e., cannot be reduced to a single expression) you can add a static method that do that for you and refer to it in the super call, something like:

Class Son extends Base {

  private static boolean getMyBoolean(int num) {
    return num > 17; //or any complex algorithm you need.
  }

  public Son (int num) {
    super(num, getMyBoolean(num));
  }
  ...
}

Otherwise, if the missing arguments can be calculated using a simple expression (as in the concrete example you give), just write:

Class Son extends Base {
  public Son (int num) {
    super(num, num > 17);
  }
  ...
}

Problem

I am trying to make the inheriting class ask for less arguments, and calculate the 'correct' mising arguments for the super class. Looking for help on how to do this, without using factory methods. This is an example code to simplify things. Son(int) will call super(int,boolean) based on the value of int. ``` class Base { ... public Base (int num, boolean boo2) { ...} ... } class Son extends Base { ... public Son (int num) { if (num > 17) super(num, true); else super(num , false); } ... } ``` I also considered making Base an interface, but that doesn't allow me to enforce some argument correctness checks. Appreciate your help.

Original source

Related problems