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
2
3
4
5
6
7
8
9
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);
}
}
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
3
4
5
6
7
8
9
10
11
12
13
14
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");
}
}
 
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

Karibasappa G C (KB)
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