Java: Constructor overloading

To support different parameter lists the constructor can be overloaded. In the example below, if the class is instantiated without any parameters the fields will be assigned default values.

With one parameter both fields will be set to that value, and with two parameters each field will be assigned a separate value.

Attempting to create an object with the wrong number of arguments or with incorrect data types will result in a compile-time error, just as with any other method.

package javaapplication19;

public class JavaApplication19 {

    static class MyRectangle {

        int x, y;

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

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

        public MyRectangle() {
            this.x = 15;
            this.y = 30;

        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: This keyword
Java: Constructor chaining >>