0
0
Javaprogramming~3 mins

Why Super keyword in Java? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could build on someone else's work without copying it all over again?

The Scenario

Imagine you have a family recipe book, and your grandma's recipe is the base. Now, you want to add your own twist to the recipe but still keep the original steps. Without a clear way to refer back to grandma's recipe, you might accidentally change or lose important parts.

The Problem

Manually rewriting or copying the original recipe every time you want to add a twist is slow and confusing. You might forget some steps or mix up ingredients, leading to mistakes and frustration.

The Solution

The super keyword acts like a direct link to grandma's original recipe. It lets you use or build upon the original instructions easily without rewriting them, keeping everything clear and organized.

Before vs After
Before
class Parent {
  void show() {
    System.out.println("Parent method");
  }
}

class Child {
  void show() {
    System.out.println("Child method");
  }
}

// To call Parent's show, you must create a Parent object separately.
After
class Parent {
  void show() {
    System.out.println("Parent method");
  }
}

class Child extends Parent {
  void show() {
    super.show(); // calls Parent's show
    System.out.println("Child method");
  }
}
What It Enables

It enables clear and easy reuse of parent class features while adding or changing behavior in child classes.

Real Life Example

Think of a car model that inherits features from a basic car but adds new ones. Using super, the new model can keep the basic car's engine setup and just add a sunroof or better tires.

Key Takeaways

Super keyword helps access parent class methods or variables.

It avoids rewriting code and reduces errors.

Makes extending and customizing classes simple and clear.