Java constructor chaining example

This example will illustrate, how the constructor chaining is achieved in Java.

public class ConstructorChaining {

    int length;
    int breadth;
    int height;

    public int getVolume() {
        return (length * breadth * height);
    }

    ConstructorChaining() {
        this(10, 10);
        System.out.println("In zero parameter Constructor");
    }

    ConstructorChaining(int length, int breadth) {
        this(length, breadth, 10);
        System.out.println("In two Parameterized Constructor");
    }

    ConstructorChaining(int length, int breadth, int height) {
        this.length = length;
        this.breadth = breadth;
        this.height = height;
        System.out.println("In threee Parameterized Constructor");
    }

    public static void main(String[] args) {
        ConstructorChaining cube1 = new ConstructorChaining();
        ConstructorChaining cube2 = new ConstructorChaining(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cube1.getVolume());
        System.out.println("Volume of Cube2 is : " + cube2.getVolume());
    }
}


Output:

In threee Parameterized Constructor
In two Parameterized Constructor
In zero parameter Constructor
In threee Parameterized Constructor
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000

No comments:

Post a Comment