In Java, the super keyword is a reference variable that is used to refer to the immediate parent class object.
It can be used to access members (variables and methods) of the superclass, call superclass constructors, and distinguish between superclass and subclass members that have the same name.
Here are the main uses of the super keyword:
We can use the `super` keyword to access variables and methods of the superclass from within the subclass.
This is useful when a subclass overrides a method from the superclass but still needs to call the superclass version of the method.
class Animal { String color = "brown"; void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void display() { System.out.println(super.color); // Accessing super class variable super.sound(); // Calling super class method } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.display(); } }
brown Animal makes a sound
class Animal { Animal() { System.out.println("Animal constructor"); } } class Dog extends Animal { Dog() { super(); // Calling superclass constructor System.out.println("Dog constructor"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); } }
We can use the `super` keyword to explicitly call a constructor of the `super` class from the constructor of the subclass.
This is useful when the `super` class constructor needs to be executed before the subclass constructor.
Animal constructor Dog constructor
class Animal { void eat() { System.out.println("Animal eats"); } } class Dog extends Animal { void eat() { System.out.println("Dog eats"); super.eat(); // Calling super class method } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); dog.eat(); } }
When a method is overridden in the subclass, we can use "super" to call the superclass version of the method.
Similarly, when a variable in the subclass hides a variable in the superclass, you can use super to refer to the superclass variable.
The super keyword plays an important role in Java inheritance, allowing subclasses to interact with their immediate superclass in various ways.
It facilitates code reuse, maintains a clear hierarchy between classes, and enables the extension of functionality in object-oriented programs.