Friday, 29 January 2016

Java Tutorial : Java super keyword (Access super class members)

Level Up Your Java Skills!

Subscribe to Ram N Java for clean, bite-sized tutorials and practical code walk-throughs!

Subscribe Now on YouTube

Understanding Superclass Members and the 'super' Keyword

In Java, when a subclass inherits from a parent class, it gains access to its parent fields and methods. However, when both classes define variables or methods with matching names, the child class members hide or override the parent class members.

The super keyword solves this naming collision by giving you direct access to the hidden fields or overridden methods of the immediate superclass.

When Should You Use 'super'?

You will use the super keyword in three common scenarios:

  • Field Shadowing: When a child class variable shares the same name as a parent class variable.
  • Method Overriding: When you need to trigger the parent class method implementation alongside the child class behavior.
  • Constructor Chaining: When you want to pass parameters directly up to the parent constructor.

Step-by-Step Code Demonstration

class Vehicle {
  int maxSpeed = 120;
}

class Car extends Vehicle {
  int maxSpeed = 180;

  void displaySpeed() {
    System.out.println("Car Speed: " + maxSpeed);          // Refers to child speed (180)
    System.out.println("Vehicle Speed: " + super.maxSpeed); // Refers to parent speed (120)
  }
}

Without prefixing super.maxSpeed, Java will resolve the variable locally from the Car class. The super reference explicitly points back up the inheritance tree.

Important Rules to Keep in Mind

  1. The super keyword belongs strictly to an instance context; you cannot use it in static methods or static blocks.
  2. It can only access immediate superclass members that are visible based on their access modifiers (public, protected, or package-private).
  3. Using super ensures cleaner, self-documenting code when writing complex class hierarchies.

Watch More Java Inheritance Tutorials:

No comments:

Post a Comment

Tutorials