ProgrammingBackend Developer

Describe how the 'super' keyword works in Java, where to apply it correctly, and what pitfalls may arise from its usage?

Pass interviews with Hintsage AI assistant

Answer.

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:

  • Call the parent constructor (it must be the first statement in the constructor)
  • Access fields and methods of the superclass, even if they are overridden in the current class

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:

  • Used to access inherited members
  • Explicitly calls the superclass constructor
  • Allows clarification of behavior when overriding

Trick questions.

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.

Common mistakes and anti-patterns

  • Excessive use of super without necessity (logic duplication)
  • Using super to access private fields or methods — will lead to a compilation error
  • Missing the call to super(), if the base class requires special initialization.

Real-life example

Negative case

A developer forgets to explicitly call super() in the constructor of the derived class, and the superclass does not have a default constructor.

Pros:

  • None

Cons:

  • Compilation error, inability to create an object

Positive case

An overridden method in a subclass first calls the super implementation and then extends it with additional logic.

Pros:

  • Maintains base behavior, making it easy to add new functionality.

Cons:

  • If the superclass changes, unexpected side effects may easily occur, requiring attention to method contracts.