分析学生类和教师类,找到老师类和学生类当中的共性内容,抽取出一个父类,用继承的方式编写一个父类(Person), 两个子类:学生类(Student)和教师类(Teacher);用java写
时间: 2024-01-24 11:16:44 浏览: 81
以下是Java代码:
```
public class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public void introduce() {
System.out.println("My name is " + name + ", I am " + age + " years old, and I am " + gender + ".");
}
}
public class Student extends Person {
private int grade;
private String major;
public Student(String name, int age, String gender, int grade, String major) {
super(name, age, gender);
this.grade = grade;
this.major = major;
}
public void study() {
System.out.println("I am studying " + major + " in grade " + grade + ".");
}
}
public class Teacher extends Person {
private String subject;
private String title;
public Teacher(String name, int age, String gender, String subject, String title) {
super(name, age, gender);
this.subject = subject;
this.title = title;
}
public void teach() {
System.out.println("I am teaching " + subject + " as a " + title + ".");
}
}
```
在这个例子中,我们发现学生类和教师类都有姓名、年龄和性别这三个属性,因此我们将它们抽象出来成为父类Person。学生类和教师类分别继承了父类Person,同时又有各自的特有属性和方法。通过继承,我们可以减少代码的重复,并且方便后续的修改和维护。
阅读全文