What is the purpose of Java’s super keyword?

I have seen the super keyword used in Java, but I am not clear about when or why I should use it. Can someone explain what it is used for and give an example of how it is used?

Add Comment
1 Answer(s)
The `super` keyword in Java is a reference variable used to refer to the immediate parent class object. It is primarily used in two scenarios: 1. **Method Overriding** - If a method is overridden in a child class, the `super` keyword allows you to call the method of the parent class from the overridden method in the child class. 2. **Constructor Invocation** - During constructor chaining, you can use the `super` keyword to call the parent class constructor from the child class's constructor. As a rule, this call to the parent class constructor must be the first line in the child class constructor. For example, consider this parent class: ```java class ParentClass { void display() { System.out.println("ParentClass display"); } } ``` And this child class: ```java class ChildClass extends ParentClass { void display() { super.display(); // this calls the display method of ParentClass System.out.println("ChildClass display"); } } ``` If you create an object of the `ChildClass` and call its `display` method, it first calls the parent class's `display` method with `super.display()`, then continues with its own implementation, outputting: ``` ParentClass display ChildClass display ``` For constructor invocation: ```java class ParentClass { ParentClass(){ System.out.println("ParentClass Constructor"); } } class ChildClass extends ParentClass { ChildClass(){ super(); // this calls the ParentClass constructor System.out.println("ChildClass Constructor"); } } ``` When you create an object of `ChildClass`, it will first call the `ParentClass` constructor, then its own: ``` ParentClass Constructor ChildClass Constructor ``` Remember that `super` can also be used to access parent class fields if they are hidden by fields in the child class, but accessing fields this way is generally considered bad practice because it breaks encapsulation.
Answered on July 17, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.