Using Constructors

A constructor initializes an object during creation.
It has the same name as the class.
Constructors have no return type (not even void).
The Rectangle class in the following uses a constructor to set the dimensions:
 
class Rectangle {
  double width;
  double height;

  Rectangle() {
    width = 10;
    height = 10;
  }

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

public class Main {
  public static void main(String args[]) {
    Rectangle mybox1 = new Rectangle();
    double area;
    area = mybox1.area();
    System.out.println("Area is " + area);

  }
}

When this program is run, it generates the following results:


Area is 100.0

Constructors with Parameters

The constructors can also have parameters. Usually the parameters are used to set the initial states of the object.

 
class Rectangle {
  double width;
  double height;

  Rectangle(double w, double h) {
    width = w;
    height = h;
  }

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

public class Main {
  public static void main(String args[]) {
    Rectangle mybox1 = new Rectangle(10, 20);
    double area;
    area = mybox1.area();
    System.out.println("Area is " + area);
  }
}

The output from this program is shown here:


Area is 200.0

Constructors with object parameters

 
class Rectangle {
  double width;
  double height;

  Rectangle(Rectangle ob) { // pass object to constructor
    width = ob.width;
    height = ob.height;
  }

  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
  }

  // constructor used when cube is created
  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 myclone = new Rectangle(mybox1);
    double area;
    // get volume of first box
    area = mybox1.area();
    System.out.println("Area of mybox1 is " + area);
    // get volume of clone
    area = myclone.area();
    System.out.println("Area of clone is " + area);

  }
}

The output:


Area of mybox1 is 200.0
Area of clone is 200.0
Home 
  Java Book 
    Class  

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