Search code examples
javainheritanceconstructorsupermappedsuperclass

Java Constructor of a Subclass


I have a subclass extending a superclass. If constructor in super class has parameters a,b,c like MySuperClass(int a, string b, string c). And the constructor in the subclass has parameters a,d,e like MySubClass(int a, int d, int e), what should go inside the constructor of the subclass? Can I say super(a) so I don't have to duplicate the code for parameter a? but the constructor of super has 3 parameters; so I think I cannot do that.

Also, if I just ignore using super and assign the fields to parameters (like this.fieldName=parameterName) I would get the error that "there is no default constructor in super" why do I get this even though the super class has a constructor?

public abstract class Question {

    // The maximum mark that a user can get for a right answer to this question.
    protected double maxMark;

    // The question string for the question.
    protected String questionString;

    //  REQUIRES: maxMark must be >=0
    //  EFFECTS: constructs a question with given maximum mark and question statement
    public Question(double maxMark, String questionString) {
        assert (maxMark > 0);

        this.maxMark = maxMark;
        this.questionString = questionString;
    }
}

public class MultiplicationQuestion extends Question{

    // constructor
    // REQUIRES: maxMark >= 0
    // EFFECTS: constructs a multiplication question with the given maximum 
    //       mark and the factors of the multiplication.
    public MultiplicationQuestion(double maxMark, int factor1, int factor2){
        super(maxMark);
    }
}

Solution

  • The first thing a constructor always does is to call its superclass' constructor. Omitting the super call doesn't circumvent this - it's just syntactic sugar that saves you the hassle of specifying super() (i.e., calling the default constructor) explicitly.

    What you could do is pass some default value to the superclass' constructor. E.g.:

    public class SubClass {
        private int d;
        private int e;
    
        public SubClass(int a, int d, int e) {
            super(a, null, null);
            this.d = d;
            this.e = e;
        }
    }