Use of super keyword in Java


The super keyword is another important one. This is a reference variable that is used to call the immediate parent class. This keyword is expensive when we talk about Inheritance and Polymorphism. There are three uses of the 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 to the variables of the immediate parent class.
  • 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 the super keyword to invoke the constructor of the immediate parent class 
  • 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 the parent class, you can use super keyword.
  • In overriding, it will call the child class method instead of the 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();
   }
}




Use of super keyword in Java Use of super keyword in Java Reviewed by Ravi Yasas on 12:41 PM Rating: 5

No comments:

Powered by Blogger.