Overloading Constructors

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

 
class Rectangle {
  double width;
  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:


200.0
1.0
49.0
Home 
  Java Book 
    Class  

Constructors:
  1. Using Constructors
  2. Overloading Constructors
  3. Invoking Overloaded Constructors Through this( )