Wednesday, July 13, 2016

Use of super keyword in Java


Super keyword is another important one. This is a reference variable which is used to call immediate parent class. This keyword is expensive when we talk about Inheritance and Polymorphism. There are three uses of super keyword. 
  1. super with variables
  2. super with constructors
  3. super with method overriding 

Super with variables

  • If you use super with instance variables, it will refer the variables of immediate parent class (More about variables).
  • Look at the following example.
Parent.java

package com.app.superDemo;

public class Parent {
 
   String s = "Parent";
 
   public String showMessage() {
       return s;
   }
}


Child.java

package com.app.superDemo;

public class Child extends Parent {
 
   public String showMessage() {
       return super.s;
   }
}


Application.java

package com.app.superDemo;

public class Application {
 
   public static void main(String[] args) {
       Child child = new Child();
       System.out.println(child.showMessage());
   }
}


Super with constructors

  • We can use super keyword to invoke the constructor of immediate parent class (More about constructors)
  • Once you instantiate a class, the compiler calls the default constructor of that class.
Parent.java

package com.app.superDemo;

public class Parent {
   public Parent() {
       System.out.println("Parent");
   }  
}


Child.java

package com.app.superDemo;

public class Child extends Parent {

   public Child() {
       super();
       System.out.println("Child");
   }
}

Application.java

package com.app.superDemo;

public class Application {
 
   public static void main(String[] args) {
       new Child();
   }
}


Super with method overriding

  • If you want to call methods in parent class, you can use super keyword.
  • In overriding it will call child class method instead of parent class.
  • Look at the following example.
Parent.java

package com.app.inheritance;

public class Parent {

   public void ShowMessage(){
      System.out.println("Parent");
   } 
}


Child.java

package com.app.inheritance;

public class Child extends Parent {

   public void ShowMessage(){
       super.ShowMessage();
       System.out.println("Child");
   }
}

Application.java

package com.app.inheritance;

public class Application {
 
   public static void main(String[] args) {
       Child child = new Child();
       child.ShowMessage();
   }
}