Java super Keyword

Java "super" Keyword

The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.

Whenever you create an instance of a subclass, an instance of the parent class is created implicitly, which is referred to by the super reference variable.


Uses of super Keyword

  1. To access data members (attributes) of the parent class: This is useful if the parent and child classes have members with the same name.
  2. To call methods of the parent class: This is used for method overriding, when you want to call the parent's version of the method from the child's overridden method.
  3. To call the constructor of the parent class: super() can be used to call the parent class's constructor.

Example: Calling the Superclass Constructor

One of the most common uses of super is to call the constructor of the parent class from the child class's constructor. This is essential when the parent class does not have a default (no-argument) constructor.

The call to super() must be the very first statement in the child class constructor.

Using `super()` in a Constructor

class Vehicle {
  String brand;

// Parent class constructor public Vehicle(String brand) { this.brand = brand; System.out.println("Vehicle constructor called."); }

public void displayBrand() { System.out.println("Brand: " + brand); } }

class Car extends Vehicle { String model;

// Child class constructor public Car(String brand, String model) { // Call the parent constructor using super() super(brand); this.model = model; System.out.println("Car constructor called."); }

public void displayModel() { System.out.println("Model: " + model); } }

public class Main { public static void main(String[] args) { // Creating an object of the subclass will call both constructors Car myCar = new Car("Ford", "Mustang"); myCar.displayBrand(); myCar.displayModel(); } }

In this example, super(brand) in the Car constructor calls the Vehicle(String brand) constructor, ensuring that the brand attribute from the parent class is properly initialized.


Example: Calling a Superclass Method

You can use super to call a method from the parent class, even if you have overridden it in the child class.

Calling a Superclass Method

class Animal {
  public void eat() {
    System.out.println("This animal eats food.");
  }
}

class Dog extends Animal { @Override public void eat() { super.eat(); // Calls the parent's eat() method System.out.println("This dog eats dog food."); } }

// In main, you would call it like this: // Dog myDog = new Dog(); // myDog.eat();