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.
- 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); } }
- 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
- 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.
- super.<variableName>
super.<variableName>
used to access variable defined in Parent class.