Trusted answers to developer questions

What is the super keyword in Java?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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.

svg viewer

Examples


1. Accessing base class variables

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 Class
class Base {
int num = 30;
}
// Derived Class
class Derived extends Base {
int num = 20;
void callThis() {
// print `num` of both classes
System.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();
}
}

2. Invoking base class method

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 Class
class Base {
void display(){
System.out.println("Base Class");
}
}
// Derived Class
class Derived extends Base {
// invoke `display()` method for both the classes
void 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();
}
}

3. Invoking base class constructor

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

// Base Class
class Base {
Base(){
System.out.println("Base Class Constructor");
}
}
// Derived Class
class Derived extends Base {
// invoke `display()` method for both the classes
Derived(){
super();
System.out.println("Derived Class Constructor");
}
}
/* Driver Routine */
class Test {
public static void main(String[] args) {
Derived temp = new Derived();
}
}

RELATED TAGS

java
inheritance
classes
parent
reference
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?