1
0

Constructors in Java

A constructor is a special method that 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. The main purpose of the constructor is to set the initial state of an object when the object is created with the help of new operator. Once defined, the constructor is automatically called immediately after the object is created. Constructors look a little strange because they have no return type, not even void. This is because the implicit return type of a 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.

A Constructor has the following general syntax:

<accessibility modifier> <class name> (<formal parameter list>) <throw clause>
{
    <local variable declaration>
    <statements>
}

Let’s begin by defining a simple constructor that simply sets the instance variables to some values. This version is shown here:

Program to implement constructor in Java

class College
{
    int year;
    int phone;
    int pin_code;
    College() // class name and constructor name is same
    {
        year=1999;
        phone=2204156;
        pin_code=147205;
    }
    void show()
    {
        System.out.println("Year of Establishment="+year);
        System.out.println("Phone Number="+phone);
        System.out.println("Pin_code="+pin_code);
    }
}
class ConstructorDemo
{
    public static void main(String c[])
    {
        College col=new College(); //constructor automatically called
        col.show();
    }
}

When the program run, it generates the following results:

Year of Establishment=1999
Phone Number=2204156
Pin_code=147205

As you can see, col is initialized by the College() constructor when it was created. Since the constructor gives values to all the instance variables and values can be seen with the help of show() method called col as col.show().

Constructor declarations are very much like method declarations. However, the following restrictions on constructors should be noted:

  • Modifiers other than <accessibility modifiers> are not permitted in the constructor header.
  • Constructors cannot return value and hence, cannot specify a return type, not even void, in the constructor header, but they can contain the simple form of the return statement in the constructor body.
  • The Constructor name must be the same as the class name.

Default Constructor

A default constructor is a constructor without any parameters. In other words, it has the following signature:

<class name> ()

There are two kinds of default constructors exist i.e. implicit default constructor and explicit default constructor. In the following code, the class Light does not specify any constructor.

Class Light
{
    int Watts;
    boolean indicator;
    String location;
}
class Greenhouse
{
    public static void main(String st[])
    {
        Light oneLight=new Light(); // Call of Implicit Default Constructor
    }
}

The above code will create an object oneLight using new operator with the help of an implicit default constructor and will initialize the fields of the object with their default values. (i.e. 0 for Watts, false for indicator, and null for location).

Now in the following code, the class Light provides an explicit default constructor.

class Light
{
    int Watts;
    boolean indicator;
    String location;
    Light()
    {
        Watts=40;
        indicator=true;
        location="Wall";
    }
}
class Greenhouse
{
    public static void main(String args[])
    {
        Light oneLight=new Light(); // call to explicit default constructor
    }
}

The above code will create an object oneLight using new operator with the help of an explicit default constructor and will initialize the fields of the object with their values 40 for Watts, true for indicator, and Wall for location.

Constructors with Arguments

While the Light() constructor in the preceding example does initialize a oneLight object, it is not very useful – all objects have the same dimensions. What is needed is a way to construct oneLight objects of various dimensions. The easy solution is to add parameters to the constructor. As you can probably guess, this makes them much more useful. For example, the following version of Box defines a parameterized constructor which sets the dimensions of a box as specified by those parameters. Pay special attention to how Box objects are created.

Program to implement constructors with arguments in Java

class Box
{
    double width;
    double height;
    double depth;
    Box(double w, double h, double d) // This is a constructor for Box.
    {
        width=w;
        height=h;
        depth=d;
    }
    double volume() // compute and return volume
    {
        return width*height*depth;
    }
}
class BoxDemo
{
    public static void main(String args[])
    {
        Box mybox1=new Box(10,20,15); // declare, allocate, and initialize Box objects
        Box mybox2=new Box(3,6,9);
        double vol;
        vol=mybox1.volume(); // get volume of first box
        System.out.println("Volume is " + vol);
        vol=mybox2.volume(); // get volume of second box
        System.out.println("Volume is " + vol);
    }
}

The output from this program is shown here:

Volume is 3000.0
Volume is 162.0

As you can see, each object is initialized as specified in the parameters of its constructor. For example, in the following line,

    Box mybox1 = new Box(10, 20, 15);

the values 10, 20, and 15 are passed to the Box() constructor when new creates the object. Thus, mybox1’s copy of width, height, and depth will contain the values 10, 20, and 15, respectively.

‘this’ keyword

When a method needs to refer to the object within it that invoked it ‘this’ keyword is used. The 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 as a reference to an object of the current class type. To better understand what this refers to, consider the following version of College():

// A redundant use of this.
class College
{
    int year;
    int phone;
    long pin_code;
    College(int a, long int b, long int c)
    {
        this.year=a;
        this.phone=b;
        this.pin_code=c;
    }
    ....
}

This version of College() operates exactly like the earlier version. The use of this is redundant but perfectly correct. Inside College(), this will always refer to the invoking object. While it is redundant in this case, this is useful in other contexts.

Program to demonstrate the use of ‘this’ for returning the current object:

class Number
{
    int n;
    Number()
    {
        n=0;
    }
    Number increment()
    {
        n++;
        return this;
    }
    void display()
    {
        System.out.println("Number = "+n);
    }
}
class TestNumber
{
    public static void main(String args[])
    {
        Number x=new Number();
        Number y=new Number();
        y.display();
        y=x.increment(); // value of n is incremented for x objectv and assigned to y
        y.display();
    }
}

Output:

Number = 0
Number = 1

If we remove the statement return this; from increment() method the statement y=x.increment() will cause compilation error. Also, the return type of increment() method is of type Number, Hence it must return an object of Number class, but this method does not define any object of Number class and use this keyword to return the current object.

Leave a Reply