12 Jun 2015

Calling a Constructor Explicitly in Java

Inside a constructor we can call another constructor explicitly by using super or this keyword, where this is to call another constructor in the same class and super is to call another constructor of super class.

Let's see how to call another constructor by using this and super keyword with an example.

Calling another constructor in the same class (using this keyword)
class Person{
   String name;
   
   public Person(){
      this("John");   // Explicit Constructor Invocation
   }

   public Person(String name){
      this.name = name;
   }

   public void displayMyName(){
      System.out.println(this.name);
   }
}

public class Test{
   public static void main(String args[]){
      Person p1 = new Person();
      p1.displayMyName();
   }
}
In the preceding program initially Person class default constructor is called and from within it we are calling Person class single-argument constructor explicitly as this("John").

Calling another constructor of super class (using super keyword)
class Employee{
   Integer id;
 
   public Employee(Integer id) {
      this.id = id;
   }
}

class Person extends Employee{   
   public Person(){
      super(101);   // Explicit Constructor Invocation
   }

   public void displayMyId(){
      System.out.println(this.id);
   }
}

public class Test{
   public static void main(String args[]){
      Person p1 = new Person();
      p1.displayMyId();
   }
}
In the preceding program initially sub class (Person) default constructor is called and from within it we are calling super class (Employee) single-argument constructor explicitly as super(101).

Points to Remember:
  1. Calling a constructor statement must always be the first statement inside a constructor
  2. Based on the number and the type of arguments the compiler determines which constructor to call
  3. Make sure to avoid recursive constructor invocation
    class Person{
       public Person(){
          this();   // Recursive Constructor Invocation
       }
    }
    
    The above code causes recursive constructor invocation which is illegal and throws compile-time error





Popular Posts

Write to Us
Name
Email
Message