Instantiating inherited Constructor

I have two classes A (superclass) and B (subclass) as shown below. I used super() keyword along with parameters to instantiate the constructor of the super class. However, I'm looking another elegant way of doing this rather than listing all the parameters of the super class in the sub class since it becomes lengthy when the number of attributes for the super class is huge.

public class A {

    private String a1;
    private String a2;
    private String a3;

    public A (String a1, String a2, String a3){
        this.a1 = a1;
        this.a2 = a2;
        this.a3 = a3;
    }

    public void setA1(String a1){
        this.a1 = a1;
    }

    public String getA1(){
        return a1;
    }
    ...
}

public class B extends A{

    private String b1;
    private String b2;
    private String b3;

    public B (String b1, String b2, String b3, String a1, String a2, String a3){
        super(a1,a2,a3);
        this.b1 = b1;
        this.b2 = b2;
        this.b3 = b3;
    }

    public void setB1(String b1){
        this.b1 = b1;
    }

    public String getB1(){
        return b1;
    }
    ...
}
Jon Skeet
people
quotationmark

However, I'm looking another elegant way of doing this rather than listing all the parameters of the super class in the sub class since it becomes lengthy when the number of attributes for the super class is huge.

Well, the elegant way is to avoid having a "huge" number of parameters. If you find that you have a large number of parameters, consider:

  • Splitting the class in two (or more) pieces, as often a large number of parameters is a sign that a class has more than one responsibility
  • The builder pattern (or some variety of it), which would avoid this duplication and make construction clearer

Constructors aren't inherited in Java, and there's no way to make them inherited.

people

See more on this question at Stackoverflow