Super Keyword in Java Explained

Super Keyword in Java Explained

23 Oct 2024
Beginner
879 Views
13 min read
Learn with an interactive course and practical hands-on labs

Java Online Course Free with Certificate

Understanding the super Keyword in Java

The super keyword is one of the most important features of Java. However, Java is an object-oriented programming language with strong inheritance management and the utilization of features. The super keyword is an essential feature of Java inheritance since it allows a subclass to communicate with its superclass.

In this Java tutorial, we will learn all about the super keyword in Java including the usage of the super keyword in Java, and the advantages of the super keyword in JavaSo remove all your distractions, and let's focus on What is the super Keyword?

Fast-track your full-stack development journey by enrolling in our Java Full Stack Developer Certification Course now!

What is the super Keyword in Java?

  • In Java, the super keyword enables referencing a subclass's parent or superclass. 
  • It is frequently used to gain access to superclass members (fields or methods) that the subclass has overridden. 
  • Super.methodName() allows you to invoke the superclass's method from within a subclass.
  • In order to initialize inherited members, super() is also used to invoke the superclass constructor from the subclass constructor. 
  • To put it briefly, this super keyword is essential for programmers who wish to preserve inheritance hierarchies and allow code reuse in object-oriented programming.
Related Article: - What Is this Keyword in Java?

Usage of Java Super Keyword

It is mostly used in the following three ways :

  1. Use of super with Variables(Access the variables and methods of the superclass)
  2. Use of super with Methods(Address naming problems between members of the superclass and subclass)
  3. Use of super with Constructors(Invoke the constructor of the superclass)

What is the super Keyword?

1. Use of super keyword with Variables

The super keyword can be used to access the variable in the superclass if the subclass has a variable with the same name as the superclass's variable.

class Animal {
    String name = "Animal";
}
class Dog extends Animal {
    String name = "Dog";

    void display() {
        System.out.println("Name in superclass: " + super.name);
        System.out.println("Name in subclass: " + name);
    }
}
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.display();
    }
}    

Output

Name in superclass: Animal
Name in subclass: Dog

2. Use of Super keyword with Methods

When a subclass has a method with the same name as a method in its superclass, the super keyword can be used to call the superclass's version of the method.
class Animal {
    void display() {
        System.out.println("I am an animal lover");
    }
}

class Dog extends Animal {
    void display() {
        System.out.println("I have a dog");
    }

    void printMessage() {
        super.display();  // Calls the display() method of Animal class
        display();        // Calls the display() method of Dog class
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.printMessage();
    }
}    

Output

I am an animal lover
I have a dog

3. Use of super keyword with Constructors

Superclass Constructor Invoking:
The superclass constructor can also be called by using the super keyword. This is especially helpful if you want to initialize the superclass with specific values or if the superclass lacks a no-argument constructor.
class Animal {
    Animal(String name) {
        System.out.println("Animal constructor called: " + name);
    }
}

class Dog extends Animal {
    Dog(String name) {
        super(name);  // Calls the constructor of Animal class
        System.out.println("Dog constructor called");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog("Buddy");
    }
}   

Output

Animal constructor called: Buddy
Dog constructor called

Features of Super Keyword in Java

  • A subclass's constructor needs to call the parent class's constructor when it is created, which is why super is used to call a superclass constructor. Using the super() keyword, which invokes the parent class' constructor, this is achieved.
  • To invoke a superclass method, use super: The super keyword allows a subclass to invoke a method specified in its parent class. This comes in handy when the subclass wishes to call the method's implementation from the parent class in addition to its own.
  • To access a superclass field, use super: The super keyword allows a subclass to access a field declared in its parent class.
  • A constructor's super statement needs to come first: The super() declaration needs to come first in the subclass constructor when calling a superclass constructor.
  • The use of super in a static situation is prohibited: In a static context, like a static method or a static variable initializer, the super keyword is not permitted.
  • It is possible to call a parent class method using the super keyword, although it is not required. If a method is called without the super keyword, if it isn't overridden in the subclass, it will call the implementation of the parent class.

A real-world example of super keyword in Java

In Java, the super keyword is used to access superclass methods and constructors. Let's create an example with Employee and Company classes to illustrate its usage in our Java Compiler
// Superclass Company
class Company {
    String companyName;
    int companySize;

    Company(String companyName, int companySize) {
        this.companyName = companyName;
        this.companySize = companySize;
    }

    void displayCompanyInfo() {
        System.out.println("Company Name: " + companyName);
        System.out.println("Company Size: " + companySize + " employees");
    }
}

// Subclass Employee extending Company
class Employee extends Company {
    String employeeName;
    int employeeId;

    Employee(String companyName, int companySize, String employeeName, int employeeId) {
        super(companyName, companySize); // invoking superclass constructor
        this.employeeName = employeeName;
        this.employeeId = employeeId;
    }

    void displayEmployeeInfo() {
        super.displayCompanyInfo(); // invoking superclass method
        System.out.println("Employee Name: " + employeeName);
        System.out.println("Employee ID: " + employeeId);
    }
}
// Main class to demonstrate
public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee("DotNetTricks Innovation.", 500, "Sourav Kumar", 1001);
        emp.displayEmployeeInfo();
    }
}

Output

Company Name: DotNetTricks Innovation.
Company Size: 500 employees
Employee Name: Sourav Kumar
Employee ID: 1001

Explanation

The use of the super keyword in this case facilitates code reuse and maintains the separate hierarchy between the Employee and Company classes by providing access to the superclass constructor and method from the subclass.

Advantages of Using Super Keyword

1. Access to Superclass Members

  • This feature helps resolve naming disputes and guarantees that the right version is used by granting access to superclass variables and functions, even when they are overridden in a subclass.

2. Constructor Chaining

  • By calling the superclass constructor via super(), the object is guaranteed to be in a consistent state and allows for the correct initialization of inherited elements prior to subclass-specific initialization.
Read More: Constructor Chaining in Java

3. Maintaining Inheritance

  • By preserving and improving the behavior of parent classes, it promotes code reuse and preserves the "is-a" relationship in inheritance.

4. Error Prevention

By using superclarifies intents, the chance of inadvertently overriding or concealing superclass members is decreased. Specifically mentioning constructors or members of superclasses helps prevent logical mistakes.
Conclusion
The super keyword gives subclasses a means of using the features of their superclasses, improving the readability, maintainability, and reusability of code. Any Java programmer who wants to become an expert in object-oriented programming has to understand and utilize the super keyword properly. Also, consider our Java Full Stack Developer Course for a better understanding of other Java concepts.

FAQs

The primary purpose of the "this" keyword is to refer to the current object, while the "super" keyword allows access to the members of the parent class.

Nope, we can't. Main method is a static method and therefore it belongs to the class, not to the instance of this class (object).

Both this() and super() can not be used together in constructor. this() is used to call default constructor of same class.it should be first statement inside constructor. super() is used to call default constructor of base class.it should be first statement inside constructor.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this