Java Constructor

Java allows objects to initialize themselves whenever they are created. This automatic initialization is performed by the use of a constructor.

A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically same to a method. Once defined, the constructor is automatically called whenever an object is created, before the new operator completes.

Constructor look a little strange because they have no any return type, not even void. This is because the implicit return type of a class constructor is the class type itself. It's 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.

Java Constructor Example

Now let's start by defining a simple constructor that simply sets the dimensions of each box to the same values :

/* Java Program Example - Java Constructor
 * In this program, Box uses a constructor to 
 * initialize the dimensions of a box  
 */

class Box
{
    double width;
    double height;
    double depth;
    
    /* this is the constructor for the Box */
    Box()
    {
        System.out.println("Constructing Box");
        width = 100;
        height = 100;
        depth = 100;
    }
    
    /* calculate and return the volume */
    double volume()
    {
        return width * height * depth;
    }
}

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

When the above Java program is compile and executed, it will produce the following output:

java constructors

As you will see that both mybox1 and mybox2 were initialized by the Box() constructor when they were created. Since the constructor gives same dimensions to all the boxes, 100 by 100 by 100, both mybox1 and mybox2 will have the same volume. The statement println() inside the Box() is for the sake of illustrations only.

Most constructors will not display anything rather they will just initialized an object.

Before moving on, let's first examine the new operator. As you know, when you allocate an object, you use the below general form :

class-var = new classname();

Now you can understand why the parentheses are needed after the class name. What is actually going on is that the constructor for the class is being called. Thus, in the line

Box mybox1 = new Box();

new Box() is calling the constructor Box(). When you do not explicitly define a constructor for a class, then Java creates a default constructor for the class that's why the preceding line of code worked in earlier versions of Box that didn't define a constructor.

The default constructor automatically initializes all the instance variables to their default values, that are zero, null, and false, for numeric types, reference types, and boolean, respectively. The default constructor is often sufficient for the simple classes, but it usually won't do for more sophisticated ones. Once you define your own constructor, then the default constructor is no longer used.

Parameterized Constructor in Java

While the constructor Box() in the previous example does initialize a Box object, it is not very useful, all the boxes have the same dimensions. The simple solution is to add parameters to the constructor.

As you can likely guess, this makes it much more useful. For instance, here this version of Box defines a parameterized constructor that sets the dimension of a box as specified by those parameters. Pay special attention on how Box objects are created.

Java Parameterized Constructor Example

Here is an example program, illustrates the concept and use of parameterized constructor in Java:

/* Java Program Example - Java Constructors
 * In this program, Box uses a parameterized
 * constructor to initialize the dimensions 
 * of a box                        
 */

class Box
{
    double width;
    double height;
    double depth;
    
    /* this is the constructor for Box */
    Box(double wid, double hei, double dep)
    {
        System.out.println("Constructing Box");
        width = wid;
        height = hei;
        depth = dep;
    }
    
    /* compute and return the volume */
    double volume()
    {
        return width * height * depth;
    }
}

class BoxDemo
{
    public static void main(String args[])
    {
        
        /* declare, allocate, and initialize Box objects */
        Box mybox1 = new Box(100, 200, 150);
        Box mybox2 = new Box(30, 60, 90);
        
        double vol;
        
        /* get the volume of the first box */
        vol = mybox1.volume();
        
        /* print the volume of the first box */
        System.out.println("Volume of the first box is " + vol);
        
        /* get the volume of the second box */
        vol = mybox2.volume();
        
        /* print the volume of the second box */
        System.out.println("Volume of the second box is " + vol);
        
    }
}

When the above Java program is compile and executed, it will produce the following output:

Above Java Programming Output:
parameterized constructors in java

As you can see, the values 100, 200, and 150 are passed to the constructor Box() whenever new creates the object. Therefore, mybox1's copy of width, height, and depth will contain the values 100, 200, and 150, respectively.

Java Online Test


« Previous Tutorial Next Tutorial »