Super keyword in java

In this section we will discuss about the super keyword in java. Super is a keyword defined in java. Super is used to refer the variable, methods and constructor of the super or parent class.

Super keyword in java

Super keyword in java

In this section we will discuss about the super keyword in java. Super is a keyword defined in java. Super is used to refer the variable, methods and constructor of the super or parent class. If we override one of the super class method ,then we can invoke the super class method using "super" keyword. Here is the example to use super to call super class methods.

    class superclass
    {
     public void demo()
      {
      System.out.println("In super class");
      }
   }

Now, Here is a subclass that override demo() method.

   public class subclass extends superclass
   {
      public void demo()
      {
       super.demo();  //override demo method in superclass
       System.out.println("In sub class ");
      }
      public static void main(String args[])
       {
        Subclass sb=new Subclass();
        sb.demo();
       } 
    }  

So, to refer the demo() method in the superclass super is used in the subclass and the output will be the following.

In super class

In sub class

Super is also used to call super class constructor, default constructor is called by super() with no args and parameterized constructors super(parameter) with arguments. The following example illustrate how to use super to call superclass constructors.

class superclass
 {
     superclass()
     {
	  System.out.println("In superclass constructor");
     }
     
   }
     public class Subclass extends superclass
     {
    	 Subclass()
    	 {
    		 super();  //calling superclass constructor
    		 System.out.println("In sub class constructor");
    	 }
        
    	 public static void main(String args[])
       {
        Subclass sb=new Subclass();
      
        } 
     }  

Output :  After compiling and executing output will be as follows:

In superclass constructor

In sub class constructor

Note : While calling super class constructor in sub class, super() should be the first statement. super() with no args is automatically created by compiler while object creation.