super keyword in java

The "super" keyword refers to the super-class of the class in which the keyword is used.

It is used to access variables and methods of a super class from a sub class.

  1. public class Person{
  2.     protected int age;
  3.      
  4.     protected displayAge() {
  5.         System.out.println("Age = " + age);
  6.     }
  7.  
  8. Person(String name){
  9.        System.out.println("Person constructor for "+name);
  10. }
  11. }
public class Person{
    protected int age;
     
    protected displayAge() {
        System.out.println("Age = " + age);
    }

Person(String name){
       System.out.println("Person constructor for "+name);
}
}

  1.  
  2. public class Employee extends Person{
  3.  
  4. protected String empId;
  5.     public void displayEmployee() {
  6.         super.age= 30;
  7.         super.displayAge();
  8.  
  9.  System.out.println("EmpId= " + empId);
  10.     }
  11.  
  12. Employee (){
  13.       super("John");
  14.       System.out.println("Employee constructor");
  15. }
  16. }
 
public class Employee extends Person{

protected String empId;
    public void displayEmployee() {
        super.age= 30;
        super.displayAge();

 System.out.println("EmpId= " + empId);
    }

Employee (){
      super("John");
      System.out.println("Employee constructor");
}
}


In the above example, the class Employee accesses the variable age and calls the method displayAge() of its super class Person.

Sub-class Employee also calls super class Person’s constructor using super keyword as below

super(“John”);

super as a standalone statement represents a call to a constructor of the super-class

  1. super.<methodName>()
super.<methodName>()

used call the method of the super-class.

This usage is only necessary when calling a method that is overridden in this class in order to specify that the method should be called on the superclass.

  1. super.<variableName>
super.<variableName>

used to access variable defined in Parent class.

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on