Java: Constructor chaining

The this keyword can also be used to call one constructor from another. This is known as constructor chaining, and allows for greater code reuse.

Note that the keyword appears as a method call, and that it must be on the first line in the constructor.

package javaapplication19;

public class JavaApplication19 {

    static class MyRectangle {

        int x, y;

        public MyRectangle(int x) {
            this(x, x);

        public MyRectangle() {
            this(15, 30);

        public MyRectangle(int x, int y) {
            this.x = x;
            this.y = y;

        public int getArea() {
            return x * y;

    public static void main(String[] args) {

        MyRectangle r = new MyRectangle(10, 20);

        int area = r.getArea();

        MyRectangle r1 = new MyRectangle(10);
        int area1 = r1.getArea();

        MyRectangle r2 = new MyRectangle();
        int area2 = r2.getArea();




Series Navigation<< Java: Constructor overloading
Java: Default constructor >>