Background:
In the early versions of Java, an inheritance mechanism was introduced, allowing a child class to extend the behavior of its parent class. The keyword super is used to access members of the parent class, inherited from C++.
Problem:
Sometimes there is a need to explicitly refer to a method or field of the parent class if they have been overridden or hidden. Without the proper use of super, errors or incorrect behavior may occur, for example, when working with constructors.
Solution:
With super, you can:
Example:
class Animal { void makeSound() { System.out.println("Animal sound"); } } class Dog extends Animal { void makeSound() { super.makeSound(); // Animal sound System.out.println("Bark"); } }
Key features:
Can the super call be not the first statement of the constructor?
No. The call to the parent constructor using super() must be the first statement of the constructor. If this restriction is violated, the compiler will generate an error.
Can super be used in static methods or contexts?
No. The keyword super is only applicable in non-static (instance) contexts, as it relates to the object hierarchy, not classes.
Can you access a private method of the parent through super?
No. Private methods are not visible to descendants — even through super. Only public, protected, and package-private methods or fields can be accessed through super.
A developer forgets to explicitly call super() in the constructor of the derived class, and the superclass does not have a default constructor.
Pros:
Cons:
An overridden method in a subclass first calls the super implementation and then extends it with additional logic.
Pros:
Cons: