How I call one constructor from another in Java?

How I call one constructor from another in Java ?

Hey Tom, Any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor. Example-

Class Test {
    Test() {
        this(8); // calls the constructor with integer args, Test(int a)
    }
    Test(int a) {
        this(8.5); // call the constructor with double arg, Test(double a)
    }
    Test(double a) {
        System.out.println("constructor");
    }
}

This is known as constructor overloading. Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.

1 Like