Java super Keyword

‮igi.www‬ftidea.com

In Java, the super keyword is used to refer to the parent class or call a method in the parent class. It can be used in two ways:

  1. Accessing Parent Class Members: The super keyword can be used to access the members (fields or methods) of the parent class from within the subclass. This is useful when a subclass needs to access or override a member of its parent class. For example:
class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

class Cat extends Animal {
    @Override
    public void makeSound() {
        super.makeSound(); // Call the makeSound() method of the parent class
        System.out.println("Meow");
    }
}

In this example, the makeSound() method in the Cat class overrides the makeSound() method in the Animal class, but also calls the makeSound() method in the parent class using the super keyword.

  1. Calling Parent Class Constructor: The super keyword can also be used to call the constructor of the parent class from within the constructor of the subclass. This is necessary when the parent class has a constructor that takes arguments, and those arguments need to be passed to the constructor of the subclass. For example:
class Animal {
    public Animal(String name) {
        // Initialize the animal's name
    }
}

class Cat extends Animal {
    public Cat(String name) {
        super(name); // Call the constructor of the parent class with the name argument
    }
}

In this example, the Cat class has a constructor that takes a name argument, which is passed to the constructor of the parent class using the super keyword.

Overall, the super keyword is an important part of Java inheritance that allows subclasses to access and override members of their parent class, and call the constructor of their parent class when necessary.