The super Keyword: Accessing Superclass Members
You'll learn: How to use super to explicitly refer to fields and methods defined in your parent class.
What Is super?
When a subclass inherits from a superclass, it gains access to the parent's fields and methods. But what if the subclass defines a field or method with the same name as one in the superclass? Or what if you simply want to be crystal clear that you're calling the parent's version?
That's where super comes in. Just like this refers to the current object, super refers to the superclass portion of the current object.
Using super to Access Superclass Members
You use super followed by a dot and the member name:
class Animal {
String name = "Generic Animal";
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
String name = "Generic Dog"; // hides Animal's name
void displayNames() {
System.out.println("Dog name: " + name); // Dog's field
System.out.println("Animal name: " + super.name); // Animal's field
}
void makeSound() {
super.makeSound(); // Call Animal's version
System.out.println("Woof!");
}
}
When Is This Useful?
- Overridden methods: When your subclass replaces a method but still wants to run the parent's logic first
- Hidden fields: When both classes have a field with the same name (though this is rare and often discouraged)
- Clarity: To explicitly document that you're calling inherited behavior
Key Takeaway: The super keyword lets you reach up to your superclass to access its fields and methods, even when your subclass has members with the same names.