ProAnswers.org

How to declare object parameters for constructors?

Just like methods in a class the constructors can not only accept primitive type parameters it can also have the object parameters. Object parameters contains more information and can help us initialize the class.

The following Rectangle class has a constructor whose parameter is a Rectangle class. In this way we can initialize a rectangle by the data from another rectangle.

 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);
 
  }
}