What is super keyword in Java: Explanation and Examples
super keyword is used to refer to the parent class of the current object. It allows access to the parent class's methods, constructors, and variables, especially when they are overridden or hidden in the child class.How It Works
Imagine you have a family tree where a child inherits traits from their parents. In Java, classes can inherit from other classes, called parent or superclass. The super keyword acts like a direct link to the parent, letting the child class access or call things that belong to the parent.
For example, if a child class has a method with the same name as the parent, using super lets you call the parent's version instead of the child's. It also helps when you want to use the parent's constructor to set up the object before adding more details in the child.
This keyword helps keep things clear and organized, especially when you want to build on or change behavior inherited from a parent class.
Example
This example shows a parent class Animal and a child class Dog. The Dog class uses super to call the parent constructor and method.
class Animal { String name; Animal(String name) { this.name = name; } void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { Dog(String name) { super(name); // Calls Animal constructor } @Override void sound() { super.sound(); // Calls Animal's sound method System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog("Buddy"); dog.sound(); } }
When to Use
Use super when you want to:
- Call a parent class constructor to reuse its setup code.
- Access a parent class method that is overridden in the child class.
- Refer to a parent class variable if it is hidden by a child class variable.
Real-world use cases include extending a base class with common features and customizing behavior in child classes without losing the original functionality. For example, in a game, a Character class might have basic movement, and a Player class can use super to keep that movement but add special moves.
Key Points
superrefers to the immediate parent class.- It helps access overridden methods and hidden variables.
- It is used to call parent constructors.
- Using
superkeeps code clear and avoids duplication.
Key Takeaways
super keyword accesses parent class methods, variables, and constructors.super to call overridden methods or parent constructors from a child class.super helps avoid code duplication and keeps inheritance clear.