The concept of super
keyword comes with the idea of inheritance in Java. Suppose you have a member variable or method of the same name in the derived class as you do in the base class.
When referring to that variable/method, how would the program know which one are you referring to; the base class or the derived class?
This is where super
comes into play. The super
keyword in Java acts like a reference variable to the parent class.
It’s mainly used when we want to access a variable, method, or constructor in the base class, from the derived class.
Let’s have a look at some examples to understand how exactly the super
keyword works.
When we have the data members of the same name in both the base and derived class, we can use the super
keyword to access the base class member, data
, in the derived class.
The snippet below shows how to do this:
// Base Classclass Base {int num = 30;}// Derived Classclass Derived extends Base {int num = 20;void callThis() {// print `num` of both classesSystem.out.println("Base `num`: " + super.num);System.out.println("Derived `num`: " + num);}}/* Driver Routine */class Test {public static void main(String[] args) {Derived temp = new Derived();temp.callThis();}}
When the name of a function if the same in both the base and derived class, the super
keyword can be used to invoke the base class function in the derived class.
The snippet below shows how to do this:
// Base Classclass Base {void display(){System.out.println("Base Class");}}// Derived Classclass Derived extends Base {// invoke `display()` method for both the classesvoid callThis(){super.display();display();}void display(){System.out.println("Derived Class");}}/* Driver Routine */class Test {public static void main(String[] args) {Derived temp = new Derived();temp.callThis();}}
The super
keyword can also be used to invoke the parent class constructor, both parameterized and empty, in the derived class.
// Base Classclass Base {Base(){System.out.println("Base Class Constructor");}}// Derived Classclass Derived extends Base {// invoke `display()` method for both the classesDerived(){super();System.out.println("Derived Class Constructor");}}/* Driver Routine */class Test {public static void main(String[] args) {Derived temp = new Derived();}}
Free Resources