Java Constructors

Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. This fulfills the requirement for initialization of object upon creation.

Constructors

A constructor initializes an object immediately upon creation.

  • It has the same name as the class in which it resides and is syntactically similar to a method.
  • Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes.
  • Constructors have no return type, not even void. This is because the implicit return type of a class’ constructor is the class type itself. It is the constructor’s job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.

Example:

We can modify the previous program to have default constructor as below.

// example to illustrate default constructor
class Box {
    double width;
    double height;
    double depth;
    
    //default constructor
    public Box(){
        width = 10;
        height = 10;
        depth = 10;
    }

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

class DemoConstructor {
    public static void main(String args[]) {
        //creates two Box objects
        Box mybox1 = new Box();
        Box mybox2 = new Box();
        double volume;

        volume = mybox1.volume();// get volume of first box
        System.out.println("Volume of mybox1 is " + volume);
        volume = mybox2.volume();// get volume of second box
        System.out.println("Volume of mybox2 is " + volume);
    }
}

The ouput of the program is:

Volume of mybox1 is 1000.0
Volume of mybox2 is 1000.0

Parameterized Constructors

While the Box( ) constructor in the preceding example does initialize a Box object, it is not very useful—all boxes have the same dimensions. What is needed is a way to construct Box objects of various dimensions. The easy solution is to add parameters to the constructor.

Let us modify the program presented above to add parametrized contructor.

// example to illustrate parametrized constructor.
class Box {
    double width;
    double height;
    double depth;

    //default constructor
    public Box(){
        width = 10;
        height = 10;
        depth = 10;
    }
    
    //parameterized constructor
    public Box(double width, double height, double depth) {
        this.width = width;
        this.height = height;
        this.depth = depth;
    }

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

class DemoParameterizedCons {
    public static void main(String args[]) {
        //creates two Box objects
        Box mybox1 = new Box(); //default constructor is called
        Box mybox2 = new Box(10,20,30); //parametrized constructor called
        double volume;

        volume = mybox1.volume();// get volume of first box
        System.out.println("Volume of mybox1 is " + volume);
        volume = mybox2.volume();// get volume of second box
        System.out.println("Volume of mybox2 is " + volume);
    }
}

The output of the program is:

Volume of mybox1 is 1000.0
Volume of mybox2 is 6000.0

The this Keyword

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked.

You can use this anywhere a reference to an object of the current class’ type is permitted.

To better understand what this refers to, consider the following version of Box():

// use of this keyword.
Box(double w, double h, double d) {
     this.width = w;
     this.height = h; 
     this.depth = d; 
}


Here, inside Box( ), this will always refer to the invoking object. While it is redundant in this case, this is useful in other contexts.

Instance Variable Hiding

It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes.

While it is usually easier to simply use different names, there is another way around this situation. Because this lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables.

For example, here is another version of Box( ), which uses width, height, and depth for parameter names and then uses this to access the instance variables by the same name:

// Use this to resolve name-space collisions. 
Box(double width, double height, double depth) { 
     this.width = width; 
     this.height = height; 
     this.depth = depth; 
}