Super Keyword in Java

(Last Updated On: March 7, 2019)

Learn all about Super Keyword in Java with example i.e. where super keyword can be used in java programs. For example, invoking constructor, method and variables etc. of base class from derived class in inheritance relationship.

Super keyword can be used for following concepts.

  1. Calling super class constructor from derived class.
  2. Calling immediate parent class / super class method.
  3. Initialize a base class variable from derived class.

NOTE:
Base class / super class/ parent class all are terminology for base class.
Derived class/ child class / sub class all are terminology for derived class.

PREREQUISITE: To understand the super keyword you must be familiar with following java concepts

1)Call base class constructor from derived class using super keyword in java

We use super keyword in java program to call base class constructor for derived class. You can see the example how super keyword has been used in derived class constructor to invoke base class constructor.

Important point: If the base class constructor has no parameter, then we don’t need to call super() in derived class constructor and compiler will call it implicitly.

However, if the base class constructor has parameters then you must use super keyword with parameter.

A) Calling base class constructor with no parameter from derived class using super

Java code:

 

Output:
Parent class constructor
Child class constructor

B) Calling parameterized constructor of base class from derived class using super

 

Output:
Parent class constructor Age :40
Child class constructor

 

 

2)Call Base class method from Derived class using Super Keyword

You can call a base class public method from a derived class using super keyword in java programs.

For example, consider the Parent and Child class both have mobile () methods. When you create object of child class and call mobile () method, then child class mobile method will be called. Because, Child class extends parent class and has overridden mobile method. You can refer method overriding in java programs.

So, If we want to call parent class mobile method from child class method, then we need to call the parent’s class method using super keyword.

In below java code, mobile method of parent class has been called using super keyword in child class mobile method.

 

Output:
Parent’s mobile
Child’s mobile

 

 

3) Access base class public variables from derived class using super keyword

Lets say we a common field e.g. public int account is in both class parent and child. Child class extends base class. So base call variable is also accessible to child class. But, when you print the account variable in child class, then child class variable will be printed not base class.

So, using super keyword, we can refer base class variable from child class method.

 

 

Output:
Parent’s Account: 10000
Child Account: 5000