The super Keyword in Java

Understand the super keyword in Java, its role in accessing parent class members, and how it simplifies inheritance-based programming.

super keyword in Java

Introduction

The super keyword in Java is a special reference used to access members (methods, fields, or constructors) of a parent class. It is commonly used in inheritance to distinguish between parent and child class members and to avoid ambiguity.

  • Access Parent Members: Call methods or fields of the parent class.
  • Invoke Parent Constructor: Use the parent class's constructor from a child class.
  • Handle Overriding: Access overridden methods in the parent class.

Using super to Access Fields

The super keyword is used to access fields of the parent class when they are hidden by child class fields.

super accessing fields example

Using super to Call Methods

When a method is overridden in the child class, the super keyword can be used to call the parent class's version of the method.

super calling methods example

Using super to Call Constructors

The super() call is used to explicitly invoke the parent class's constructor from the child class's constructor.

super calling constructors example

Common Pitfalls

While using the super keyword, there are a few things to watch out for:

  • Constructor Restrictions: The super() call must always be the first statement in a constructor.
  • Access Rules: Parent class members accessed using super must be accessible (e.g., not private).

super common pitfalls example

Real-World Usage

The super keyword is widely used in:

  • Constructor Chaining: Explicitly call the parent constructor to initialize inherited properties.
  • Handling Overriding: Call parent class methods when overriding in child classes.
  • Distinguishing Members: Access parent class fields or methods hidden by the child class.

Summary

The super keyword in Java is an essential tool for working with inheritance. It provides a clear way to access parent class members and ensures that inherited properties and methods are handled effectively.

navigation