Java Super Keyword

In Java, the concept of super keyword is associated with the concept of inheritance. Assume the derived class has a member variable or method with the same name as the base class. When you refer to that variable/method, how does the program know whether you mean the base class or the derived class?

The super keyword acts as a reference variable to the parent class. Used when we want to access the method, constructor, and variable in the parent class from the derived class.

  • Accessing variables of Base Class

The super keyword is used to access the base class member, and data in the derived class when both base and derived classes have data members with the same name.

Code:

Java Code

class solution{
       public static void main(String[] args) {
              Class2 obj = new Class2();  
              obj.print2();
       }
}
class Class1{
       int x = 100 ;  
}

class Class2 extends Class1{
       int x = 90 ;  
       void print2(){
              System.out.println("Class1 x: " + super.x) ; 
              System.out.println("Class2 x: " + x) ; 
       }
}

Output:

Class1 x: 100
Class2 x: 90

  • Invoking the Base Class Method

When a function’s name is identical in the base and derived classes, the super keyword can be used to call the base class function from the derived class.

Code:

Java Code

class solution {
       public static void main(String[] args) {
              Class2 obj = new Class2();
              obj.printFunction();
       }
}

class Class1 {
       void print() {
              System.out.println("Class1 print");
       }
}

class Class2 extends Class1 {
       void print() {
              System.out.println("Class2 print")  ;
       }

       void printFunction() {
              print();
              super.print()  ;
       }
}

Output:

Class2 print
Class1 print

  • Invoking Constructor

The super keyword is used to invoke the parent class constructor. Parent class can be both parameterized and empty, in the derived class.

Code:

Java Code

class solution{
       public static void main(String[] args) {
              Class2 obj = new Class2() ;  
       }
}

class Class1{
       Class1(){
              System.out.println("Class1 constructor");
       } 
}

class Class2 extends Class1{
       Class2(){
             super()  ; 
             System.out.println("Class2 constructor")  ;
      }
}

Output:

Class1 constructor
Class2 constructor

Special thanks to Shreyas Vishwakarma for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article