Home > DeveloperSection > Articles > super keyword in java

super keyword in java


Java Java 
Ratings:
0 Comment(s)
 760  View(s)
Rate this:

super keyword in java

The super keyword in java is a reference variable that is used to refer immediate parent class object. If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

In Java 'super' keyword can be used to refer superclass instance in a subclass.

In Java 'super' keyword can be used to refer superclass instance in a subclass.

Super keyword is used for two different purpose.

1.      To call the Super class constructor

Super keyword is used to execute the super class constructor in sub class constructor.

Example of super keyword to call constructor of super class in sub class

 

class Person

{

   Person()

    {

     System.out.println("Constructor of person class");

     }

 

class Employee extends Person

{

     Employee()

     {

     System.out.println("Constructor of employee class");

      }

}

 

class PermanentEmployee extends Employee

{

     PermanentEmployee()

     {

       System.out.println("Constructor of permanent employee class");

      }

}

 

class ConstructorInheritanceDemo

{

      public static void main(String args())

      {

               PermanentEmployee pObj = new PermanentEmployee();

       }

}

 

Output-:

Constructor of person class

Constructor of employee class

Constructor of permanent employee class

2.      To execute super class method

The super keyword can also be used to invoke parent class method. It should be used in case subclass contains the same method as parent class as in the example given below: 

 

class Parentclass {

      // Overridden method

      void display() {

            System.out.println("Parent class method");

      }

}

 

class Subclass extends Parentclass {

      // Overriding method

      void display() {

            System.out.println("Child class method");

      }

 

      void printMsg() {

            // This would call Overriding method

            display();

            // This would call Overridden method

            super.display();

      }

 

      public static void main(String args[]) {

            Subclass obj = new Subclass();

            obj.printMsg();

      }

}

Output:

welcome to java

 welcome


Don't want to miss updates? Please click the below button!

Follow MindStick