Java Constructors Overload

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;/*  w w  w  . j a v  a2  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:

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 {//w  ww.jav a2 s . co  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)
  }
}




















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures