Java super Keyword in Java Inheritance

‮figi.www‬tidea.com

In Java, the super keyword is used in a subclass to refer to the superclass, either to call a constructor or to call a method or field in the superclass. The super keyword is used to differentiate between the methods and fields of the subclass and those of the superclass.

Here are a few examples of how the super keyword can be used in Java inheritance:

  1. Calling a Superclass Constructor:
class Animal {
    public Animal() {
        System.out.println("An animal is born.");
    }
}

class Dog extends Animal {
    public Dog() {
        super(); // calls the constructor of the superclass
        System.out.println("A dog is born.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        // prints "An animal is born." followed by "A dog is born."
    }
}

In the example above, the Dog class calls the constructor of its superclass Animal using the super() method. This initializes the Animal object before the Dog object is initialized.

  1. Calling a Superclass Method:
class Animal {
    public void speak() {
        System.out.println("I am an animal.");
    }
}

class Dog extends Animal {
    public void speak() {
        super.speak(); // calls the speak() method of the superclass
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.speak();
        // prints "I am an animal." followed by "Woof!"
    }
}

In the example above, the Dog class calls the speak() method of its superclass Animal using the super keyword. This allows the Dog class to call the speak() method of the Animal class and then provide its own implementation of the speak() method.

The super keyword is a powerful tool in Java inheritance that allows a subclass to call and reuse the behavior of its superclass. However, it's important to use the super keyword carefully to avoid creating complex and difficult-to-understand code.