Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call superconstructor in a neat way

So here is my code:

public MyClass (int y) {
    super(y,x,x);
    //some code
}

My problem is that in this case i want to generate a 'x' and sent to the super constructor. However the call to the superconstructor must be the first line in this constructor. Of course I could do something like this:

int x;
{
    x = generateX();
}

But this feels ugly, and then the code will run no matter what constructor I use, which feels not so nice. Right now I am consider encapsulating my whole object in another object that only calculates x and then starts this object. Is this the best approach?

like image 575
pgsandstrom Avatar asked Dec 29 '25 19:12

pgsandstrom


2 Answers

How about:

public MyClass(int y) {
  this(y, generateX());
  //some code
}

private MyClass(int y, int x) {
  super(y, x, x);
  //some code
}

private static int generateX() {
  return 10;
}

If you're happy for generateX to be called twice, you don't need the extra constructor - it's just here to allow the same value to be used for both superclass constructor parameters.

like image 185
Jon Skeet Avatar answered Jan 01 '26 09:01

Jon Skeet


What about super(y, generateX(), generateX())

like image 45
Poindexter Avatar answered Jan 01 '26 09:01

Poindexter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!