What are Three Uses of Super Keyword ?

  • Post author:
  • Reading time:2 mins read

What is Super keyword ?

  1. In the Inheritance concept, when a subclass object calls its instance member function which can consist of implicit reference variables this or super.
  2. The difference between this and super is that this reference variable is of subclass type, whereas super reference variable is of superclass type.
  3. Call to super is made first prior to the constructor of the subclass. In other words, the constructor of the parent class always executes before the child class constructor.
  4. If the subclass constructor does not explicitly invoke its superclass constructor then the compiler automatically puts the super statement in the constructor of the subclass.

What are the Three Uses of Super Keyword ?

  • If a child class overrides one of its parent class’s methods, you can invoke that overridden method through the use of the keyword super. In other words, Whenever there is a method having the same name in both parent and child class. You can invoke the method of a parent class by putting the super keyword in front of the name of the overridden method which would refer to the parent’s class method.
  • Super keyword helps in resolving the name conflict between member variables of superclass and subclass having the same name.
  • Passing values through constructor while creating an object of the subclass, it is also essential to provide values to superclass variables too. For this, we can call super to pass the values to the superclass constructor.

Java program to show the usage of Super keyword

Program:

class A
{
  int z;
    A (int a)
  {
    z = a;
  } public void f1 ()
  {
  }

}

class B extends A
{
  int z;
    B (int a, int b)
  {
    super (a);    //call for super class constructor
    z = b;
  } public void f1 ()
  {
    super.f1 ();    //call for super class method } 
    public void f2 ()
    {
      super.z = 4;   //call for super class variable 
  }
      
  } 
  public class Example
  {
    public static void main (String[]args)
    {
      B obj = new B ();
      B obj = new B (5, 3);
        obj.f1 ();
        obj.f2 ();
  }
      
  }

 

Leave a Reply