javamultiple-constructors

A constructor containing another constructor of the same Class/Object


I am having a class SomeClass with the following member fields and the constructors

private int someInt;
private String someStr;
private String strTwo;

//the contructors
public SomeClass() {}

// second constructor
public SomeClass(int someInt, String someStr) {
    this.someInt = someInt;
    this.someStr = someStr;
}

// my emphasis here
public SomeClass(int someInt, String someStr, String strTwo) {
    // can i do this
    new SomeClass(someInt, someStr); // that is, calling the former constructor
    this.strTwo = strTwo;
}

Will the third constructor create the same object as:

public SomeClass(int someInt, String someStr, String strTwo) {
    this.someInt = someInt;
    this.someStr = someStr;
    this.strTwo = strTwo;
}

Solution

  • Use the this keyword to call a constructor from another constructor. If you do call another constructor, then it must be the first statement in the constructor body.

    public SomeClass(int someInt, String someStr, String strTwo) {
        // Yes you can do this
        this(someInt, someStr); // calling the former constructor
        this.strTwo = strTwo;
    }