java中设计Teacher类继承Person类
时间: 2023-05-24 12:02:50 浏览: 134
A:在Java中,可以使用关键字"extends"来实现类的继承。以下是一个示例代码,演示如何设计Teacher类继承Person类。
```
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void introduce() {
System.out.println("My name is " + name);
}
}
public class Teacher extends Person {
private String course;
public Teacher(String name, String course) {
super(name);
this.course = course;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
@Override
public void introduce() {
System.out.println("I am a teacher. My name is " + getName() + ", and I teach " + course);
}
}
```
在上面的代码中,Person类是父类,Teacher类继承自Person类。Teacher类新增了一个私有属性course,代表教授的课程。通过使用super关键字调用父类的构造方法,Teacher类在实例化时,会同时创建Person类的对象,并将name属性继承下来。在Teacher类中,我们也重写了introduce方法,以便输出更恰当的结果(指示该对象为Teacher类)。
阅读全文