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.

Also read – this keyword in java

Let’s see an example on super keyword.

class Manager
{
   int salary = 50000;
}
class Employee extends Manager
{
   int salary = 20000;
   void display(int salary)
   {
      // here refers to the parent class instance variable
      System.out.println(super.salary);
   }
   public static void main(String[] args)
   {
      Employee obj = new Employee();
      obj.display(30000);
   }
}


Output:

50000


To understand super keyword more clearly first learn polymorphism and inheritance.


use of super keyword

1.super keyword can be used to refer immediate parent class instance variable.

Refer above example.

2.super keyword can be used to invoke immediate parent class method.

For example:

class Manager
{
   void display()
   {
      System.out.println("in class Manager.");
   }
}
class Employee extends Manager
{
   void print()
   {
      super.display();
   }
   public static void main(String[] args)
   {
      Employee obj = new Employee();
      obj.print();
   }
}


Output:

in class Manager.

3.super keyword can be used to invoke immediate parent class constructor.

For example:

class Manager
{
   Manager()
   {
      System.out.println("in class Manager.");
   }
}
class Employee extends Manager
{
   Employee()
   {
      System.out.println("in class Employee.");
   }
   public static void main(String[] args)
   {
      Employee obj = new Employee();
   }
}


Output:

in class Manager.
in class Employee.

If you notice in the above example I have not used or called super keyword.

Even then parent class constructor is called first and then child class constructor is called.

This is because compiler has called super keyword implicitly.

Above output will be same if we include or exculde super keyword in the example.


Never stop learning java and coding in java. Learn core java programming.