super keyword is used for differentiating the base class features with derived class features. The super keyword in java is like a reference variable that is used to refer to parent class objects. The super keyword is used with the concept of inheritance.
super is used in the following:When a derived class and base class has same data members. In that case there is a possibility of ambiguity for the JVM. In this case we use super with variables. super keyword is placing an important role in three places. They are at variable level, at method level and at constructor level.
Program to use super at variable levelclass Vehicle{ int speed = 160; } class Car extends Vehicle { int speed = 140; void display() { /* print speed of base class (vehicle) */ System.out.println("Maximum Speed: " + super.speed); } } class Test1 { public static void main(String[] args) { Car s = new Car(); s.display(); } }Output
D:\javap>javac Test1.java D:\javap>java Test1 Maximum Speed: 160
When we want to call parent class method in child class. Whenever a parent class and child class have same named methods then to resolve this ambiguity we use super keyword.
Program to use super at method level
class Person { void message() { System.out.println("I am person class"); } } class Student extends Person { void message() { System.out.println("I am student class"); } void display() { // will invoke or call current class message() method message(); // will invoke or call parent class message() method super.message(); } } class Test4 { public static void main(String args[]) { Student s = new Student(); s.display(); } }Output
D:\javap>javac Test4.java D:\javap>java Test4 I am student class I am person class
super keyword is used to access the parent class constructor. super can also call both parametric as well as non parametric constructors depending upon the situation.
Program to use super at constructor levelclass Person { Person() { System.out.println("This is Person class Constructor"); } } class Student extends Person { Student() { // call parent class constructor super(); System.out.println("This Student class Constructor"); } } class Test5 { public static void main(String[] args) { Student s = new Student(); } }Output
D:\javap>javac Test5.java D:\javap>java Test5 This is Person class Constructor This Student class Constructor