Way2Java

Constructors and Constructor overloading

A constructor looks more like a method but without return type. Moreover, the name of the constructor and the class name should be the same. The advantage of constructors over methods is that they are called implicitly whenever an object is created. In case of methods, they must be called explicitly. To create an object, the constructor must be called. Constructor gives properties to an object at the time of creation itself (else, it takes some method calls with extra code to do the same job). Programmer uses constructor for initializing variables, instantiating objects and setting colors. Constructor is equivalent to init() method of an applet.

Default Constructor – No Argument Constructor

A constructor without parameters is called as "default constructor" or "no-args constructor". It is called default because if the programmer does not write himself, Java creates one and supplies. The default constructor supplied does not have any functionality (output).

public class Demo
{
  public Demo()
  {
    System.out.println("From default constructor");
  }
  public static void main(String args[])
  {
    Demo d1 = new Demo();
    Demo d2 = new Demo();
  }
}
Output screen of Demo.java

public Demo()

"public" is the access specifier and "Demo()" is the constructor. Notice, it does not have return type and the name is that of the class name.

Demo d1 = new Demo();

In the above statement, d1 is an object of Demo class. To create the object, the constructor "Demo()" is called. Like this, any number of objects can be created like d2 and for each object the constructor is called.

Constructor Overloading

Just like method overloading, constructors also can be overloaded. Same constructor declared with different parameters in the same class is known as constructor overloading. Compiler differentiates which constructor is to be called depending upon the number of parameters and their sequence of data types.

public class Perimeter
{
  public Perimeter()                                                     // I
  {
    System.out.println("From default");
  }
  public Perimeter(int x)                                                // II
  {
    System.out.println("Circle perimeter: " + 2*Math.PI*x);
  }
  public Perimeter(int x, int y)                                         // III
  {
    System.out.println("Rectangle perimeter: " +2*(x+y));
  }
  public static void main(String args[])
  {
    Perimeter p1 = new Perimeter();                     // I
    Perimeter p2 = new Perimeter(10);                  // II
    Perimeter p3 = new Perimeter(10, 20);             // III
  }
}

Output screen of Perimeter.java

Perimeter constructor is overloaded three times. As per the parameters, the appropriate constructor is called. To call all the three constructors three objects are created. Using this(), all the three constructors can be called with a single constructor.

this() with Constructors

Suppose by accessing one constructor, the programmer may require the functionality of other constructors also but by creating one object only. For this, Java comes with this(). "this()" is used to access one constructor from another "within the same class". Depending on the parameters supplied, the suitable constructor is accessed.

public class Perimeter
{
  public Perimeter()                                                      // I
  {
    System.out.println("From default");
  }
  public Perimeter(int x)                                                 // II
  {
    this();
    System.out.println("Circle perimeter: " + 2*Math.PI*x);
  }
  public Perimeter(int x, int y)                                          // III
  {
    this(100);
    System.out.println("Rectangle perimeter: " +2*(x+y));
  }
  public static void main(String args[])
  {
    Perimeter p3 = new Perimeter(10, 20);                                 // III
  }
}

Output screen of Perimeter.java

In the code, creating object p3, the III constructor is accessed. From III, with "this(100)" statement, the II constructor is accessed. Again from II, the I is accessed without the statement "this()". As per the parameter supplied to this(), the appropriate or corresponding constructor is accessed.

Rules of using this()

A few restrictions exist for the usage of this().

  1. If included, this() statement must be the first one in the constructor. You cannot write anything before this() in the constructor.
  2. With the above rule, there cannot be two this() statements in the same constructor (because both cannot be the first).
  3. this() must be used with constructors only, that too to call the same class constructor (but not super class constructor).


Constructors in Inheritance

Constructors come with some implicit behavior. Most of the time, the programmer would like to have the behavior and properties of super class constructor also being in subclass. For this reason, "a subclass constructor calls super class default constructor implicitly".

class Hello
{
  public Hello()
  {
    System.out.println("From Hello constructor");
  }
} 
class Test extends Hello
{
  public Test()
  {
    System.out.println("From Test constructor");
  }
} 
public class Demo extends Test
{
  public Demo()
  {
    System.out.println("From Demo constructor");
  }
  public static void main(String args[])
  {
    Demo d1 = new Demo();
  }
}

Output screen of Demo.java

In the above program Demo extends Test and in turn Test extends Hello. It is multilevel inheritance. In the main() method, we are accessing Demo() constructor by creating the object d1 of Demo class. The Demo() constructor calls implicitly Test() constructor because it is the super class of Demo. Similarly Hello is the super class of Test and thereby Test() constructor calls Hello() constructor. Now you get the output of all the three constructors. The output you get in reverse order.

super() with Constructors

We came to know in the previous program that subclass constructor calls super class constructor implicitly. Let us make the rule more clear. Either the "default or the overloaded constructor of the subclass calls super class default constructor implicitly". If the programmer would like to call the overloaded constructor of the super class from subclass constructor, he can use super(). Compiler comes to know which
super class constructor is to be called depending upon the parameter list of super().

class Test
{
  public Test()                        // I
  {
    System.out.println("From Test default");
  }
  public Test(int x)                   // II
  {
    this();
    System.out.println(x);
  }
}
public class Demo extends Test
{
  public Demo()                        // III
  {
    super(100);
    System.out.println("From Demo default");
  }
  public Demo(int x)                   // IV
  {
    this();
    System.out.println(x);
  }
  public static void main(String args[])
  {
    Demo d1 = new Demo(10);            // IV
  }
}

Output screen of Demo.java

In the above code, super class Test and subclass Demo come with two constructors each – one default and one overloaded.

this();

We know earlier, this() calls same class default constructor as there are no parameters.

super(100);

From III constructor, we are calling super class II constructor with super(100). "super(100)" calls super class matching integer parameter constructor, I.

if the statement super(100) is omitted in III, the III calls implicitly I.

Rules of using super()

Same restrictions of this() exist for the usage of super() also.

  1. If included, super() statement must be the first one in the constructor. You cannot write anything before super() in the constructor.
  2. With the above rule, there cannot be two super() statements in the same constructor (because both cannot be the first). That is, we can have only one of either this() or super() in the constructor.
  3. super() must be used with constructors only, that too to call the super class constructor from subclass constructor.