super keyword in java

Let’s learn super keyword in java.

super keyword in java

super keyword is the reference variable which is used to refer immediate parent class object.


To understand super keyword clearly first learn polymorphism and inheritance.


use of super keyword in java

1.) super keyword is used to refer immediate parent class instance variable – In the below example super keyword is used to access member of parent class. Here super keyword is used only if parent class and child class have same members or fields.

class Car
{
   String color = "white";  
} 
class Audi extends Car
{
   String color = "green";  
   void printColor()
   {
      // prints color of Audi class
      System.out.println(color);  
      // prints color of Car class
      System.out.println(super.color);  
   }
}
public class TestSuperKeyword
{
   public static void main(String[] args)
   {
      Audi obj = new Audi();
      obj.printColor();
   }
}


Output:

green
white

In the above example Car class and Audi class have same String variable ‘color’. If we print String variable ‘color’, current class String variable is printed by default. To print parent class String variable ‘color’ super keyword is used.


2.) super keyword is used to invoke immediate parent class method – In the below example super keyword is used to invoke immediate parent class method.

Invoking immediate parent class method should be used only if method is overridden.

class Car
{  
   void acclerate()
   {
      System.out.println("accelerating….");
   }
} 
class Audi extends Car
{  
   void acclerate()
   {
      System.out.println("revvingup….");
   }
   void brake()
   {
      System.out.println("braking…..");
   }
   void moving()
   {
      super.acclerate();
      brake();
   }
}
public class TestSuperKeyword
{
   public static void main(String[] args)
   {
      Audi obj = new Audi();
      obj.moving();
   }
}


Output:

accelerating….
braking…..

In the above example Car class and Audi class have accelerate() method. When this method is called from Audi class, it will call accelerate() method by default. To call parent class accelerate() method use super keyword.


3.) super keyword is used to invoke immediate parent class constructor – In the below example super keyword is used to invoke parent class constructor.

class Car
{
   Car()
   {
      System.out.println("Car constructor created.");
   }
}  
class Audi extends Car
{
   Audi()
   {
      super();
      System.out.println("Audi constructor created.");
   }
}
public class TestSuperKeyword
{
   public static void main(String[] args)
   {
      Audi obj = new Audi();
   }
}


Output:

Car constructor created.
Audi constructor created.

NOTE: compiler will add super() keyword in each class constructor automatically if there is no super() keyword or this() keyword.