用Java语言写一个定义超类,并通过继承定义子类,在子类中重写方法的例子
时间: 2024-03-13 12:42:54 浏览: 17
好的,下面是一个用Java语言编写的例子,包括定义超类`Person`和继承自`Person`的子类`Student`,并在子类中重写`Person`的`introduce`方法。
```java
// 定义超类 Person
public class Person {
public void introduce() {
System.out.println("I am a person.");
}
}
// 定义子类 Student,继承自 Person
public class Student extends Person {
@Override
public void introduce() {
System.out.println("I am a student.");
}
}
// 测试代码
public class Test {
public static void main(String[] args) {
Person person = new Person();
person.introduce();
Student student = new Student();
student.introduce();
}
}
```
输出结果为:
```
I am a person.
I am a student.
```
在此例子中,`Student`继承自`Person`,并且重写了`introduce`方法,以便实现学生特有的自我介绍方式。在测试代码中,分别创建了`Person`和`Student`对象,并调用它们的`introduce`方法,输出各自的内容。