In java, super keyword is a reference variable used to refer immediate parent class object.
Whenever, we create an instance of child/subclass, an instance of the parent class created implicitly which referred to a super reference variable.
super keyword use mainly on the below cases:
- super to refer immediate parent class instance variable.
- super to invoke the immediate parent class method.
- super() to invoke immediate parent class constructor.
See Also: Java: this Keyword
Note: In a constructor super() or this() will always be the first statement. If a constructor is not having this() or super() compiler will implicitly add it.
Example of Java super keyword
In this example, you will see highlighted lines and comments to find all uses of the super keyword.
import java.io.Serializable; public class Person{ private String name; protected String citizenship; public Person() { } public Person(String name, String citizenship) { super(); this.name = name; this.citizenship = citizenship; } public void print() { System.out.println("Citizen:"+ citizenship + ",Name:" + name); } }
public class Employee extends Person { private int employeeId; private String department; private int salary; public Employee() { } public Employee(int employeeId, String name, String department , String citizen, int salary) { // super keyword use to call parent constructor super(name, citizen); this.employeeId = employeeId; this.department = department; this.salary = salary; System.out.println("Employee Constructor Executed."); } public void print() { System.out.println("Id :" + + ", Department :" + department + ", Salary:" + salary ); //super keyword to access parent class variables System.out.println("Citizen:"+super.citizenship); //super keyword use to call parent class method super.print(); } }