代码简略思路:
声明父类
定义成员方法输出
"This is person class"
定义子类
重写父类成员方法输出
"This is student class"
定义成员方法display:
- 调用当前类成员方法
- 调用父类成员方法
在main方法中调用子类display方法
class Person {
void message() {
System.out.println("This is person class");
}
}
class Student extends Person {
void message() {
System.out.println("This is student class");
}
void display() {
message(); // 调用当前类的 message() 方法,即 Student 类中的 message() 方法
super.message(); // 使用 super 关键字调用父类的 message() 方法,即 Person 类中的 message() 方法
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.display(); // 调用 Student 类的 display() 方法
}
}
输出结果为:
This is student class
This is person class
1. `message();`:这是调用当前类 `Student` 中的 `message()` 方法。
由于 `Student` 类重写了 `Person` 类中的 `message()` 方法,因此这里会调用 `Student` 类中的 `message()` 方法,输出 "This is student class"。
2. `super.message();`:这是使用 `super` 关键字调用父类 `Person` 中的 `message()` 方法。
通过 `super` 关键字可以明确地指示调用父类的方法。
这里会调用父类 `Person` 的 `message()` 方法,输出 "This is person class"。