Super Keyword in Java | Use, Example

Super keyword in Java is a reference variable that refers to an immediate superclass object. In other words, it refers to the superclass of the current object. The keyword ‘super’ comes into the picture with the concept of inheritance in Java.

Java super keyword always represents a superclass object. Whenever we create an object of subclass, an object of superclass is created implicitly, which is referred by super reference variable.

The keyword “super” allows users to access members of a superclass in a subclass. In other words, if you want to call members of the super class explicitly from a subclass, then use the super keyword.

We can apply super keyword with variables, methods, constructors of parent class. Hence, we can call immediate data members or member functions of the parent class.

Not only that, we can also call a constructor of super class explicitly from a constructor of subclass. JVM always uses the super keyword to call the default constructor of super class implicitly from the subclass constructor.

Why do We Use Super keyword?


Let’s consider an example program to understand the need or use of super keyword in Java programming.

Suppose we have a class Person that is a superclass of Employee class. The class Employee is a subclass of Person. Look at the program code to understand better.

Example 1:

public class Person 
{ 
   int age = 50; 
} 
public class Employee extends Person 
{ 
   int age = 30; 
   void insertEmployeeAge() 
   { 
      int age = 20; 

   // Here, we have two ways to call instance variable 'age' of the person. 
   // 1st way: 
      Person p = new Person(); 
      System.out.println(p.age); // Output: 50 

   // 2nd way: 
      System.out.println(super.age); // Output: 50 
 
   // Calling Local variable. 
      System.out.println(age); 

   // Calling instance variable of the same class. 
      System.out.println(this.age); // Output: 30 
  } 
}

In the preceding example, inside the insertEmployeeAge() method of Employee class, there are two ways to call the variable ‘age’ of person class.

1st way:

In the first way, we have created an object of person class and called variable “age” of person class using reference variable p. But, this is not a good affordable option. Why?

This is because for sake of one variable here we are loading the complete class Person which is a wastage of memory unnecessarily. In other words, unnecessary memory will get allocated to other members for just calling the variable “age”.

2nd way:

In the second way, we have just called age directly by using a keyword “super” which will not waste memory unnecessarily. In this way, we have achieved our objectives as well as calling a single variable age of the person.

Thus, we can say that just to bypass the same class variables and methods while calling, we use the super keyword. It’s all about memory management.
[adinserter block=”5″]
Let’s look glance at the various uses of the super keyword in Java.

Use of Super keyword in Java


We can use super keyword in three ways:

  • We can use super to call the immediate parent class’s instance variable.
  • To call immediate parent class constructor.
  • To invoke the immediate superclass method.

For calling the superclass instance variable or method, we have two options. Look at the below figure.

Ways to call superclass variable and method through super keyword in java

Call Superclass Instance Variable using Super keyword


We can use the keyword “super” to call hidden instance variable in the subclass. When we declare an instance variable in the subclass with the same name as provided in the superclass, we cannot access instance variable of the superclass by its name in the subclass.

This is because it has the same name. To solve this problem, we use super keyword in the subclass to refer to superclass members from the subclass.

The general syntax to call superclass instance variable in the subclass using super keyword is as follows:

super.variable_name;

For example:
     super.a;  // Here, a is an instance variable.

Let’s take an example program in which we will call superclass instance variable from the subclass using super keyword.

Example 2:

package superKeyword; 
public class SuperDemo 
{ 
 // Declare an instance variable and initialize value of the variable. 
    int x = 100; 
} 
public class Sub extends SuperDemo 
{ 
 // Declare an instance variable with the same name as provided the name of an instance variable in the superclass. 
    int x = 200; 
  
    void display() 
    { 
   // Call superclass variable x. But, it will call variable x of class Sub because of the same name.
   // This is because we have created an object of class Sub. 
   // Therefore, it will print the value of the variable of the class Sub.
      System.out.println("Value of variable of Sub: " +x);  
 

   // To call superclass instance variable, we will use the super keyword as a reference variable. 
      System.out.println("Value of variable of SuperDemo: " +super.x); // x of class SuperDemo will call. 
   } 
public static void main(String[] args) 
{ 
// Create an instance of subclass Sub.
   Sub s = new Sub(); 
   s.display(); 
 } 
}
Output: 
      Value of variable of Sub: 200 
      Value of variable of SuperDemo: 100

As you can observe in this program, we have used super keyword to access data member or field of SuperDemo parent class in the Sub child class. This superclass variable has hidden inside the subclass because of the same name.

How to Call Super Constructor in Java


We know a constructor creates an instance of a class. The constructor of superclass does not inherit into the subclass. Therefore, it can only be called from the constructor of subclass using the keyword super.
[adinserter block=”2″]
In other words, we can invoke superclass constructor from within subclass constructor using super keyword. If we don’t use the super keyword to call super class constructor in any class’s constructor, Java compiler will automatically put the super at the first line in the class’s constructor to call constructor of the superclass. For example:

1. public class A
   { 
   // Default constructor put by Java compiler during the compilation.
      public A() {   
          // invisible super(); present here.
      }
   } 
2. public class X
   {
       public X( )
      {
         System.out.println("Hello Java");
         super( ); // Error because super must be at first line of constructor.
       }
    }
3. void msg( ) 
   {
       super( );  // Error as this is method where we tried to add super();
   }
4. X(int a)
   {
      super( );  // No error.
      super(10);  /// Error.
   }

Syntax to call Superclass Constructor

The general syntax to call a superclass constructor in Java using super keyword is as follows:

super(), or super(arguments);

1. In the above syntax, the statement super() calls no-argument constructor of its superclass.

2. The statement super(arguments) calls parent class constructor that matches arguments. In other words, the constructor of subclass passes arguments to superclass constructor using the super keyword.

3. The statement super() or super(arguments) must be the first line of child class constructor. Calling a parent class constructor’s name in the child class causes syntax error.

4. A constructor allows to create an object or instance of the class. Unlike the properties and methods, constructors of the parent class do not inherit in a child class.They can only be called from the constructor of child class using the keyword super.

5. When we create an instance of any class, implicitly, the constructor of the same object gets called. But internally, constructor calls superclass constructor with the help of super keyword. This process refers to constructor chaining in Java.

6. If a class extends another class, then it is better to use a no-arg constructor to make the class easy to extend and to avoid programming errors.

7. There is not any super.super in Java. It is illegal.

8. Recursion by using the super call to a constructor is a compile-time error in Java. See compile time error in the below example code:

public class B extends B
{
   // super( );  // Recursion occurs due to going on calling the same class.
}

In this example, recursion between superclass to constructor will be there because we are extending the same class itself.

Superclass Constructor Example Program


Let’s take some example programs based on the calling of superclass constructor in Java.

Example 3:

package superKeyword; 
public class Fruit 
{ 
// Fruit has defined an explicit constructor.
   public Fruit(int x) 
   { 
      System.out.println("Explicit fruit constructor defined"); 
   } 
 } 
public class Apple extends Fruit { 
public static void main(String[] args) 
{ 
 // Create an instance of class Apple.
    Apple a = new Apple(); 
 } 
}

In the above code, there is no explicitly defined constructor in class Apple. Therefore, Java compiler will implicitly add a default no-arg constructor in the class Apple because we have not defined any constructor explicitly in the Apple class.

Since Apple is the subclass of Fruit class, therefore, it will automatically call no-arg constructor of class Fruit. However, Fruit does not have a no-argument constructor because we have defined an explicit constructor.

Remember Java compiler adds a default constructor only when we do not define any constructor explicitly in the class. Therefore, the program cannot be compiled.

To compile the above code, declare a no-arg constructor in the class Fruit explicitly. Look at a glance at the program code.

Example 4:

package superKeyword; 
public class Fruit 
{ 
// Declare a no-arg constructor. 
   Fruit() 
   { 
      System.out.println("Fruit no-arg constructor"); 
   } 
// Fruit has an explicit constructor defined. 
   public Fruit(int x) 
   { 
     System.out.println("Fruit constructor"); 
   } 
} 
public class Apple extends Fruit { 
public static void main(String[] args) 
{ 
   Apple a = new Apple(); 
 } 
}
Output: 
       Fruit no-arg constructor

Let us consider the below program code on how super keyword navigates the flow of our program.

Example 5:

package superKeyword; 
public class P 
{ 
   P() 
   { 
    // Invisible super(); present here.
       System.out.println("P class's no-arg constructor"); 
   } 
   P(int x) 
   { 
      System.out.println("P class's one argument constructor"); 
   } 
   public void show() 
   { 
      System.out.println("P class's method"); 
   } 
} 
public class Q extends P 
{ 
  Q() 
  { 
    // super(); automatically added by Java compiler at compile-time.
       System.out.println("Q class's no-arg constructor"); 
   } 
 } 
public class Test { 
public static void main(String[] args) 
{ 
  // Create an object of class Q and call the method show() using reference variable obj. 
     Q obj = new Q(); 
     obj.show(); 
 } 
}
Output: 
        P class's no-arg constructor 
        Q class's no-arg constructor 
        P class's method

Explanation:

1. When JVM will execute the statement R obj = new R();, immediately, class Q’s constructor will call.

Inside class Q, by default, Java compiler will put super keyword in the first line at compile-time. super(); will call superclass no-arg constructor P(). Thus, the first output will be “P class’s no-arg constructor”.

2. After the complete execution of superclass no-arg constructor, the control of execution will again transfer to constructor Q(). In this way, the second output will be “Q class’s no-arg constructor”.

3. When obj.show(); will be executed, show() method of class Q will be called because it is available by default in class Q through inheritance. Thus, the third output is “P class’s method”.

How to Call Superclass Method in Java


We can also use the reserved word “super” to reference a method besides the constructor in the superclass. If a method of the subclass overrides one method of its superclass, the overridden method can be called through the use of a ‘super’ keyword.

In other words, the super should use in the case of method overriding. The general syntax to call super class method is as follows:

super.method_name() or super.method_name(parameters);

For example:
      super.msg();

Let’s take an example program based on the concept of calling superclass method in Java using super keyword.

Example 6:

package superKeyword; 
public class Student 
{ 
 // Overridden method. 
    void displayInfo() 
    { 
       System.out.println("I am John"); 
    } 
} 
public class School extends Student 
{ 
 // Overriding method. 
    void displayInfo() 
    { 
       System.out.println("My school's name is RSVM"); 
    } 
    void msg() 
    { 
       super.displayInfo(); // displayInfo of class Student is called. 
       displayInfo(); // displayInfo of class School is called. 
     } 
public static void main(String[] args) 
{ 
  // Create an instance of subclass School.
     School sc = new School(); 
     sc.msg(); 
  } 
}
Output: 
       I am John 
       My school's name is RSVM

Explanation:

In this example, the parent class ‘Student’ and child class ‘School’ both have displayInfo() method. Since the method of child class overrides the method ‘displayInfo’ of its parent class.

If you call displayInfo() method by using reference variable sc, it will call displayInfo() method of child class, not of parent class. This is because we have created an object for the child class and the object reference variable ‘sc’ is pointing to objects of child class.

In this case, we can use super.displayInfo() to invoke method displayInfo() defined in the parent class.


Question:

Suppose class X extends class Y, Y extends class Z, and a method msg() is defined in class Z. Can you invoke super.super.msg() from class X?

Answer: The answer is no. It is illegal to have such a chain of supers in Java.

Advantages of Super Keyword in Java


There are several advantages of using super keyword in Java programming. They are as:

(a) The main advantage of using super keyword is that it allows a subclass to access members (variables and methods) of its superclass. This is especially useful when both the superclass and subclass have members with the same name. By using super, we can explicitly refer to the superclass’s members.

(b) When a subclass constructor is invoked, the super() call is automatically added by the Java compiler if no explicit constructor call is made. This facilitates constructor chaining.

(c) When we override a method in a subclass, the super keyword is often used to call the overridden method of the superclass. It enables us to leverage the existing functionality of the superclass while adding specific functionality in the subclass.

(d) We can use the super keyword to call specific constructors of the superclass. This is especially helpful when the superclass has multiple constructors with different parameter lists. By using super(arguments), we can choose which constructor to call.

(e) If a subclass and its superclass have members with the same name, using super helps in resolving ambiguity by explicitly indicating that we want to access the superclass’s member.

(f) The super keyword helps to maintain properly inheritance hierarchy in Java.

⇐ PrevNext ⇒