开发者

How to call superconstructor in a neat way

开发者 https://www.devze.com 2022-12-24 17:37 出处:网络
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 superc

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开发者_Python百科 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?


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.


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


A builder pattern may also be relevant here. A bit heavy weight for the given example but if there is further setup to be done on MyClass it should be considered.

0

精彩评论

暂无评论...
验证码 换一张
取 消