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

StackOverflow https://stackoverflow.com/questions/22609617

Question

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 ?

Was it helpful?

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.

OTHER TIPS

Simple answer, no you cannot call both this and super(i). Java only allow you to chain one other constructor in the beginning of a constructor.

You can do what DFreeman suggested or there is another trick in Java;

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{

    {
        /*
         * Default initialization block.
         * During compile time, this block will get copy to each of the constructor.
         */
        System.out.println("Sub Constructor");
    }

    public SubClass(int i){
        super(i); 
        System.out.println("Parameterized  Sub Constructor");
    }
}

public class Inheritance {
    public static void main(String[] args) {
        SubClass sub=new SubClass(5);
    }
}

So if you have some common initialization (like assigning default values), you can take advantage of the default initialization block.

However, if need to call different parameterized constructors in a constructor you are out of luck. You will either have to restructure your constructors or call some common private initialization method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top