Any way to call the default constructor from a parameterized constructor?

mtk picture mtk · Jan 3, 2013 · Viewed 10.9k times · Source

Suppose, I have the following code

class C {
    int i;
    String s;

    C(){
        System.out.println("In main constructor");
        // Other processing
    }

    C(int i){
        this(i,"Blank");
        System.out.println("In parameterized constructor 1");
    }

    C(int i, String s){
        System.out.println("In parameterized constructor 2");
        this.i = i;
        this.s = s;
        // Other processing 
        // Should this be a copy-paste from the main contructor? 
        // or is there any way to call it? 
    }
    public void show(){
        System.out.println("Show Method : " + i + ", "+ s);
    }
}

I would like to know, Is there any way, I can call the main(default) constructor from the parametrized constructor (i.e. C(int i, String s) in this case) ?

Or I have just copy-paste the entire contents from the main(default) constructor to the parametrized one, as shown in comments in the above code?

Note

I need to call the default constructor after the variables i and s are set in the parametrized constructor, as the processing involves these variables.

Edit

I see this post, which says placing this() as the first line would call the default constructor. But I need to call it after the setting of values.

Answer

Pradeep Simha picture Pradeep Simha · Jan 3, 2013

Calling this() would work, but note this must be the first statement in constructor. For eg: Below code would be illegal and won't compile:

class Test {
    void Test() { }
    void Test(int i) {
        i = 9;
        this();
    }
}