Wednesday, 12 March 2014

What is java this() and super()


A call to super() is the first statement inserted by default in all the constructors of all the classes. A class which does not have a super class, actually has a super class called Object. A call to super() means calling the default constructor of the super class. This is necessary because before initializing a class the super class should be initialized. A user can also call a parametric constructor from a constructor eg: super(1). Note here super(1) should be the first statement in the constructor.

The this() call is a call to a constructor of the same class. This also should be the first  statement in the constructor. If this statement occurs in a constructor then the call to super() is omitted.



Below examples explains their working.

public class Animal {

 public  Animal(){
  System.out.println("Animal constructur called");
 }
}


public class Dog extends Animal{

 public Dog(int i){
  this();
  System.out.println("Dog constructur called");
 }
 public Dog(){
  System.out.println("Dog deault constructur called");
 }
 
}

public class Test {

 public static void main(String[] args) {
  Dog dog = new Dog(1);
 }
}

Animal constructur called
Dog deault constructur called
Dog constructur called

public class Animal {

 public  Animal(int i){
  System.out.println("Animal constructur called");
 }
}
public class Dog extends Animal{

 public Dog(int i){
  this();
  System.out.println("Dog constructur called");
 }
 public Dog(){
  super(1);
  System.out.println("Dog deault constructur called");
 }
 
}


Share the post