How to Use Java’s super Keyword to Access Base-Class Members
This tutorial demonstrates how the super keyword lets a subclass invoke overridden methods and access shadowed fields in its superclass, providing step‑by‑step Java code examples, execution results, and explanations of the underlying inheritance mechanics.
When a subclass overrides a method or a field from its superclass, the super keyword can be used to refer back to the original member defined in the base class.
Calling an Overridden Method
First, define a base class Animal with a method eat() that prints "正在吃".
public class Animal {
public void eat() {
System.out.println("正在吃");
}
}Next, create a subclass Mouse that extends Animal and overrides eat(). Inside the overridden method, super.eat() is called before printing its own message.
public class Mouse extends Animal {
// Override the eat() method from Animal
public void eat() {
// Call the superclass method
super.eat();
System.out.println("mouse 正在吃");
}
}Finally, a test program creates a Mouse instance and invokes eat():
public class MouseTest {
public static void main(String[] args) {
Mouse mouse = new Mouse();
mouse.eat();
}
}The program outputs:
正在吃
mouse 正在吃This shows that super.eat() successfully calls the original method defined in Animal before executing the subclass’s additional logic.
Accessing an Overridden Field
If a subclass defines a field with the same name as one in its superclass, the superclass field becomes hidden. The super keyword can retrieve the hidden field.
class Father {
public String s = "父类";
}
class Son extends Father {
public String s = "子类";
public void info() {
System.out.println(s); // prints subclass field
System.out.println(super.s); // prints superclass field
}
}
public class SonTest {
public static void main(String[] args) {
Son son = new Son();
son.info();
}
}The execution result is:
子类
父类Thus, super.s accesses the hidden field from Father, while s refers to the field in Son.
These examples illustrate the practical use of super for both method overriding and field shadowing in Java inheritance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
