Constructors Overloading

In this chapter you will learn:

  1. How to overload a constructor
  2. How to invoke overloaded constructors through this()

Overload a constructor

Method overloading is to declare two or more methods with the name but different type or count of parameters.

In addition to overloading normal methods, you can also overload constructor methods. In the following code Rectangle defines three constructors to initialize the dimensions of a rectangle in various ways.

class Rectangle {
  double width;/*from   ja v a 2 s . c o m*/
  double height;

  // constructor used when all dimensions specified
  Rectangle(double w, double h) {
    width = w;
    height = h;
  }

  // constructor used when no dimensions specified
  Rectangle() {
    width = -1; // use -1 to indicate
    height = -1; // an uninitialized
  }


  Rectangle(double len) {
    width = height = len;
  }

  double area() {
    return width * height;
  }
}

public class Main {
  public static void main(String args[]) {
    Rectangle mybox1 = new Rectangle(10, 20);
    Rectangle mybox2 = new Rectangle();
    Rectangle mycube = new Rectangle(7);


    double area = mybox1.area();
    System.out.println(area);

    area = mybox2.area();
    System.out.println(area);

    area = mycube.area();
    System.out.println(area);

  }
}

The output produced by this program is shown here:

Invoking Overloaded Constructors Through this()

In Java this keyword can call the overloaded constructors. The general form is shown here:

this(arg-list)

When this() is executed, the overloaded constructor that matches the arg-list is executed first.

The call to this() must be the first statement within a constructor.

The following code defines a class named MyClass. It has three constructors. The first constructor accpets two int values. The second accepts one int type value. The third one accepts no value.

class MyClass {//from j a  v  a 2 s. c  om
  int a;
  int b;

  // initialize a and b individually
  MyClass(int i, int j) {
    a = i;
    b = j;
  }

  // initialize a and b to the same value
  MyClass(int i) {
    this(i, i); // invokes MyClass(i, i)
  }

  // give a and b default values of 0
  MyClass() {
    this(0); // invokes MyClass(0)
  }
}

Next chapter...

What you will learn in the next chapter:

  1. What are the four types of nested class
  2. How to declare and use Static Member Classes