Super keyword in Java

In Java, the super keyword is used to refer to the immediate parent class. It allows subclasses to access parent class variables, methods, and constructors, especially when they are hidden or overridden.

Why super matters?

  • Helps avoid ambiguity when parent and child have members with the same name.
  • Ensures clarity in inheritance hierarchies.
  • Promotes code reusability by allowing subclasses to leverage parent functionality.
  • Prevents confusion when overriding methods.

Examples of the super keyword

Let us see some examples of the super keyword in Java:

1. Access Parent Class Variables

If both parent and child classes have variables with the same name, super.variableName helps access the parent’s version.

Let us see an example:

class Parent {
    int num = 100;
}

class Child extends Parent {
    int num = 200;

    void show() {
        System.out.println("Parent num: " + super.num); // 100
        System.out.println("Child num: " + num);        // 200
    }

    public static void main(String[] args) {
        Child obj = new Child();
        obj.show();
    }
}

Output

Parent num: 100
Child num: 200

2. Call Parent Class Methods

When a method is overridden in the child class, super.methodName() can invoke the parent’s version.
Let us see an example:

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Cat extends Animal {
    void sound() {
        super.sound(); // Calls Animal’s sound()
        System.out.println("Cat Meows");
    }

    public static void main(String[] args) {
        Cat c = new Cat();
        c.sound();
    }
}

Output

Animal makes a sound
Cat Meows

If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Read More:

Java Polymorphism
Java - Abstract Classes & Interfaces
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment