super keyword in java

  • super keyword in java is defined as a reference variable which is responsible to refer to the immediate parent class object.
  • super keyword can be only be discussed with context to inheritance
  • super keyword in generally used to access parent class members (attributes, constructors and methods)
  • Whenever an object (instance) of child class is created, an instance of parent class is created implicitly by the compiler.

Uses of super keyword in java

Uses of super keyword can be discussed with the following context:

  1. use of super as a data member
  2. use of super as a member function
  3. use of super as a constructor

1. super keyword as a data member

  • When super keyword is used with a data member in a class, then it is used to refer immediate parent class instance variable.
  • It is used to differentiate the data member of parent class as well as child class which have same fields.
  • Let us discuss with a practical example:
Class Bank { int roi=6; }
class Axis extends Bank { int roi=7; void display_roi() { System.out.println("Rate of interest in Bank class="+ super.roi +" %"); System.out.println("Rate of interest in Axis class="+ roi +" %"); } }
class Test {
public static void main(String args[]) { Axis a=new Axis(); a.display_roi(); }
}

Output:

Rate of interest in Bank class=6 %

Rate of interest in Axis class=7 %

2. super keyword as a member function

  • when super keyword is used as a member function in inheritance, then it refers to its immediate parent class methods.
  • It is used to invoke parent class method, even when a parent class as well as child class has same method name.
  • It is generally used when method is overridden.
class Bank { void roi() { System.out.println("Rate=4%"); } } class Sbi extends Bank { void roi() { System.out.println("Rate=5%"); } void calculate() { super.roi(); roi(); } public static void main(String arg) {
Sbi s=new Sbi();
s.calculate(); }
} 

Output:

Rate=4%

Rate=5%

3. super as a constructor

  • super keyword in java is also used to invoke parent class constructor.
  • when super is used as a constructor in inheritance then, an instance of parent class is implicitly called first by the compiler than creating an instance of child class.
  • When there is no super() in the constructor then the compiler adds a super() to the constructor by default.
  • super() must be the first statement in the constructor.
  • Let us understand the implementation of super keyword as a constructor.
class Bank { Bank() { System.out.println("I am in Parent class Bank"); } }
class Sbi extends Bank { Sbi() {
super(); // invokes parent class constructor
System.out.println("I am in Child class Sbi"); } }
class Test { public static void main(String args[]) { Sbi s=new Sbi(); } }

Output:

I am in Parent class Bank

I am in Child class Sbi