Super Keyword in Java

super is a keyword in java which refers to the immediate parent class object. Unlike this reference which refers to current object, super refers to immediate parent class object.

For Example, Let's say class A extends class B. Whenever you create an object of A, then "this" will have reference of object of A whereas parent class object is referenced by "super".

Uses of super Keyword in Java
  • super is used to call constructor of immediate parent class.

  • super is used to access instance variables of immediate parent class.

  • super is used to call methods of immediate parent class.

Using super to call constructor of parent class

We can use super in the constructor of subclass to call the constructor of parent class. We can call parameterized constructor of parent class by passing appropriate argument while calling super class constructor.

  • If we don't call parent class's constructor from base class explicitly, then compiler automatically ads a default constructor of parent class in every constructor of subclass.

  • super must be the first statement inside the constructor of subclass.

  • When we create an object of subclass then constructor of parent class gets called first then constructor of subclass.

Syntax
  • super(); is used to call the no-argument constructor of parent class.

  • super(...); is used to call parametrized constructor of parent class.

Using super to access instance variable of parent class

We can use super to access the instance variables of immediate parent class. It is useful when parent and child class have fields with same name and we want to access field of parent class from subclass. If we don't use super reference in subclass then JVM will always refer to subclass variable and base class variable will be hidden from subclass.


Using super to invoke instance method of parent class

We can use super to access overridden method of parent class. Sometimes, we override few methods of parent class in subclass as a result we have to use super reference in subclass to call overridden method of parent class to avoid ambiguity.
If a parent class method is not overridden in subclass then we do not need to use super to call parent class method.