Search code examples
javainheritanceparameterizeddefault-constructor

Is it possible to call both default and parameterized constructors of SubClass and SuperClass for a particular instance(parameterized) in Java?


I'm trying for the below scenario:

public class SuperClass {
    public SuperClass(){
        System.out.println("Super Constructor");
    }
    public SuperClass(int i){
        this();
        System.out.println("Parameterized Super Constructor");
    }
}
public class SubClass extends SuperClass{
    public SubClass(){
        System.out.println("Sub Constructor");
    }
    public SubClass(int i){
        super(i); /* Need to call **this()** here .. Is this possible? */
        System.out.println("Parameterized  Sub Constructor");
    }
}
public class Inheritance {
    public static void main(String[] args) {
        SubClass sub=new SubClass(5);
    }
}

How to call both default and parameterized constructors for this case ?


Solution

  • If you have functionality in the non-parameterized constructor that you need to call for both, then I'd recommend that you just move it out of there into a, for example, private void init() function that both constructors can call.