How to handle default values ​​in an inheritance chain without writing duplicate code?

So, let's say I have a class A, which is defined as follows:

 public class A{
    private int x;

    public A(){
        this(13);
    }
    public A(int x){
        this.x = x;
    }
}

And then I have a class B that needs to implement y, like this:

public class B extends A{
    private int y;

    public B(){

    }
    public B(int x){
        this(x, 0);
    }
    public B(int x, int y){
        super(x);
        this.y = y;
    }
}

My question is: what should I do in public B()? I call super () so that A assigns a default value / does everything and then does another this.y = yin this constructor, or am I calling this(13)?

Both approaches seem to require some bad methods. I write one of them this.y = yin two places. Another requires me to repeat the default value (s), and it will need to be changed every time the default value changes.

+4
source share
2

, , . , :

class A{
  private int x = 13;
  public A(){
    //use default value for x
  }
  public A(int x){
    this.x = x;
  }
}

class B extends A {
  private int y = 0;
  public B(){ 
    //use default value for x and y
  }
  public B(int x){
    super(x);
    //use default value for y
  }
  public B(int x, int y){
    super(x);
    this.y = y;
  }
}
+1

, . , , .

public class A{

    public A(){

    }

    public A(String text){

    }

}

public class B extends A{

    public B(){
        //having nothing is same as super();
        //here you can also call the other constructor
        //super(""); is allowed
    }

    public B(String text){
        //having nothing is same as super();
        //but if you add a super(text) then you set this instance to super(text); instead
    }

}

public class C{

    public C(String text){

    }

}

public class D extends C{

    public D(){
        super();// this is incorrect and will not compile
    }

    public D(String text){
        super(text);//this is fine
    }

}

, .

0

All Articles