BCA / B.Tech 9 min read

The `super` Keyword in Java

What is the `super` Keyword in Java?

The super keyword is a reference variable used inside a subclass to refer to the members (variables, methods, and constructors) of its immediate superclass. It is essential for accessing and reusing code from the parent class, especially when the subclass has members with the same name.

The Three Main Uses of `super`:
  1. To access superclass instance variables: Used when a subclass and superclass have variables with the same name.
  2. To invoke superclass methods: Used to call a method from the parent class, especially when the subclass has overridden it.
  3. To invoke the superclass constructor: Used to call the constructor of the parent class from the subclass constructor.

Comprehensive Example:

// Superclass
class Animal {
    String color = "White"; // 1. Superclass instance variable

    Animal() { // 3. Superclass constructor
        System.out.println("Animal is created");
    }

    void eat() { // 2. Superclass method
        System.out.println("Animal is eating...");
    }
}

// Subclass
class Dog extends Animal {
    String color = "Black"; // Subclass instance variable with the same name

    Dog() {
        super(); // 3. Invokes the parent class constructor (Animal())
        System.out.println("Dog is created");
    }
    
    void printColor() {
        System.out.println("Dog color is: " + color); // Prints color of Dog class
        System.out.println("Animal color is: " + super.color); // 1. Accesses color of Animal class
    }

    @Override
    void eat() {
        System.out.println("Dog is eating bread...");
        super.eat(); // 2. Invokes the parent class eat() method
    }
}

public class TestSuper {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.printColor();
        d.eat();
    }
}
        
Output of the example:
Animal is created
Dog is created
Dog color is: Black
Animal color is: White
Dog is eating bread...
Animal is eating...