The super keyword itself does not create polymorphism, but it plays an important role when method overriding is involved. It allows a subclass to access the original implementation of a method or variable from its parent class, even when that member has been overridden in the child class.
Key Points: • Polymorphism is achieved through method overriding and dynamic method dispatch. • super allows a subclass to call the parent class version of an overridden method. • It helps extend parent behavior instead of completely replacing it. • super can be used to access parent class methods, variables, and constructors. • It is useful when both parent and child implementations are needed.
Example: Suppose a parent class provides a general implementation of a method, and a child class overrides it with specialized behavior. The child class can still invoke the parent's implementation using super.
Code Example:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
super.makeSound();
System.out.println("Dog barks");
}
}
public class Demo {
public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound();
}
}Output:
Animal makes a sound Dog barks
How super Supports Polymorphism:
1. The Animal reference points to a Dog object. 2. At runtime, Java calls Dog's overridden makeSound() method. 3. Inside the overridden method, super.makeSound() invokes the parent implementation. 4. Both parent and child behaviors are executed.
Real-World Example:
Consider a Payment class with a processPayment() method.
• Payment → Logs common payment information. • CreditCardPayment → Performs credit card processing.
The child class may call:
super.processPayment();
to execute common logic before adding its own specialized behavior.
Benefits of Using super with Overriding:
• Reuses parent class logic • Avoids code duplication • Enhances maintainability • Allows extension of existing functionality • Makes inheritance hierarchies more flexible
Interview Tip: A concise interview answer is:
"The super keyword does not implement polymorphism directly, but it complements polymorphism by allowing a subclass to access the parent class implementation of an overridden method. This enables developers to extend existing behavior while still leveraging runtime polymorphism."