Java Constructors Overload

In this chapter you will learn:

  1. How to overload a constructor
  2. Example - Java Constructors Overload
  3. How to invoke overloaded constructors through this()

Description

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.

Example

In the following code Rectangle defines three constructors to initialize the dimensions of a rectangle in various ways.

 
class Rectangle {
  double width;//from  w w  w.j a  va2s.com
  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:

Example 2

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 accepts two int values. The second accepts one int type value. The third one accepts no value.


class MyClass {/*  www  .  jav  a  2  s.c  o m*/
  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 is the difference between pass-by-value vs pass-by-reference
  2. Example - Pass-by-value
  3. Example - Pass-by-reference