What Is Use Of "Super" Keyword In Java?

Earlier we have talked about method overriding concept in java during THIS POST to change the implementation of parent class's method in sub class. In inheritance, Super keyword is used to refer object of immediate parent class. Generally we are using super keyword in inheritance for three different purpose. Let's see how and when to use super keyword in java. Interviewer can ask you this question so please understand how it works.

super keyword usage
  1. To refer to the variable of parent class.
  2. To invoke the constructor of immediate parent class.
  3. To refer to the method of parent class.
Let's take one example to understand above three things. We have parent class Animal and it's sub class Elephant as bellow.

Animal.java
public class Animal {
 int age = 40;
 Animal(){
  System.out.println("Animal is moving.");
 }
 
 void welcome(){
  System.out.println("Welcome to Animal class.");
 }
}



Elephant.java
public class Elephant extends Animal {
 int age = 100;

 Elephant() {
  // To invoke parent class constructor Animal().
  super();
  System.out.println("Elephant is running.");

  welcome();
  // Used super.welcome() to call parent class method.
  super.welcome();
 }

 void showAge() {
  System.out.println("Average age of Elephant : " + age);
  // Used super.age to access parent class variable value.
  System.out.println("Average age of Animals : " + super.age);
 }

 void welcome() {
  System.out.println("Welcome to Elephant class.");
 }

 public static void main(String[] args) {
  Elephant c = new Elephant();
  c.showAge();
 }
}

Output
Animal is moving.
Elephant is running.
Welcome to Elephant class.
Welcome to Animal class.
Average age of Elephant : 100
Average age of Animals : 40

In above example you can see that we have used
  1. super.age to refer parent class variable age.
  2. super() to invoke immediate parent class constructor Animal() and
  3. super.welcome() to access parent class method.
This way you can invoke constructor of parent class in to child class or access parent class variable or method when same name method or variable is available in child class.

<< PREVIOUS || NEXT >>

2 comments: