Constructor

Constructor

  • It has the same name as the class in which it resides.
  • Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes.
  • Constructors look a little strange because they have no return type, not even void.

Example 

class Box {
 double width;
 double height;
 double depth;

// This is the constructor for Box.
 Box() {
 System.out.println("Constructing Box");
 width = 10;
 height = 10;
 depth = 10;
 }

// compute and return volume
 double volume() {
 return width * height * depth;
 }
}

class BoxDemo6 {
 public static void main(String args[]) {
 // declare, allocate, and initialize Box objects
 Box mybox1 = new Box();
 Box mybox2 = new Box();
 double vol;
 // get volume of first box
 vol = mybox1.volume();
 System.out.println("Volume is " + vol);
 // get volume of second box
 vol = mybox2.volume();
 System.out.println("Volume is " + vol);
 }
}

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

Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0

Parameterized Constructors

class Box {
 double width;
 double height;
 double depth;

// This is the constructor for Box.
 Box(double w, double h, double d) {
 width = w;
 height = h;
 depth = d;
 }

// compute and return volume
 double volume() {
 return width * height * depth;
 }
}

class BoxDemo7 {
 public static void main(String args[]) {
 // declare, allocate, and initialize Box objects
 Box mybox1 = new Box(10, 20, 15);
 Box mybox2 = new Box(3, 6, 9);
 double vol;
 // get volume of first box
 vol = mybox1.volume();
 System.out.println("Volume is " + vol);
 // get volume of second box
 vol = mybox2.volume();
 System.out.println("Volume is " + vol);
 }
}

The output from this program is shown here:
Volume is 3000.0
Volume is 162.0

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑