Is it possible to call one constructor from another in Java?

Technology CommunityCategory: JavaIs it possible to call one constructor from another in Java?
VietMX Staff asked 3 years ago
Problem

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how?

Yes, it is possible usingĀ this(args):

public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}

The preferred pattern is to work from the smallest constructor to the largest like:

public class Cons {

    public Cons() {
        // A no arguments constructor that sends default values to the largest
        this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
    }

    public Cons(int arg1, int arg2) {
       // An example of a partial constructor that uses the passed in arguments
        // and sends a hidden default value to the largest
        this(arg1,arg2, madeUpArg3Value);
    }

    // Largest constructor that does the work
    public Cons(int arg1, int arg2, int arg3) {
        this.arg1 = arg1;
        this.arg2 = arg2;
        this.arg3 = arg3;
    }
}