Java class Constructors

Introduction

A constructor initializes an object during creation.

It has the same name as the class and is similar to a method.

The constructor is automatically called when the object is created.

Constructors have no return type, not even void.

The constructor initializes the internal state of an object.

The following code uses the constructor to initialize the dimensions of a lego block

//LegoBlock uses a constructor to initialize the dimensions of a lego.
class LegoBlock {
  double width;//  w  w  w.  ja  va  2  s .  co  m
  double height;
  double depth;

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

  // compute and return volume
  double volume() {
    return width * height * depth;
  }
}
  
public class Main {
  public static void main(String args[]) {
    // declare, allocate, and initialize LegoBlock objects
    LegoBlock myLegoBlock1 = new LegoBlock();
    LegoBlock myLegoBlock2 = new LegoBlock();

    double vol;

    // get volume of first lego
    vol = myLegoBlock1.volume();
    System.out.println("Volume is " + vol);

    // get volume of second lego
    vol = myLegoBlock2.volume();
    System.out.println("Volume is " + vol);
  }
}

Parameterized Constructors

The following code creates a parameterized constructor that sets the dimensions of a lego block.

// LegoBlock uses a parameterized constructor to 
// initialize the dimensions of a lego block.
class LegoBlock {
  double width;//from   w  w w. j  a  va 2 s.  c om
  double height;
  double depth;

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

  // compute and return volume
  double volume() {
    return width * height * depth;
  }
}
  
public class Main {
  public static void main(String args[]) {
    // declare, allocate, and initialize LegoBlock objects
    LegoBlock myLegoBlock1 = new LegoBlock(10, 20, 15);
    LegoBlock myLegoBlock2 = new LegoBlock(3, 6, 9);

    double vol;

    // get volume of first box
    vol = myLegoBlock1.volume();
    System.out.println("Volume is " + vol);

    // get volume of second box
    vol = myLegoBlock2.volume();
    System.out.println("Volume is " + vol);
  }
}



PreviousNext

Related