20、编写一个类Test01.java,实现以下内容: 1)设计两个类Student1(属性:学号)和Teacher(属性:工号,方法:教学) 2)抽取两个类共同的内容(如:属性-姓名、性别,方法:吃饭、睡觉)封装到一个类Person中,各自特有的部分保留在各自类中。 3)让学生类继承Person类,老师类也继承Person。 4)实现测试类Test01,测试Student1类和Teacher是否继承了Person类的成员。20、编写一个类Test01.java,实现以下内容: 1)设计两个类Student1(属性:学号)和Teacher(属性:工号,方法:教学) 2)抽取两个类共同的内容(如:属性-姓名、性别,方法:吃饭、睡觉)封装到一个类Person中,各自特有的部分保留在各自类中。 3)让学生类继承Person类,老师类也继承Person。 4)实现测试类Test01,测试Student1类和Teacher是否继承了Person类的成员。
时间: 2024-01-11 21:05:21 浏览: 71
以下是实现代码:
Person.java
```
public class Person {
private String name;
private String gender;
public void eat() {
System.out.println("I am eating.");
}
public void sleep() {
System.out.println("I am sleeping.");
}
//getter and setter methods
}
```
Student1.java
```
public class Student1 extends Person {
private String studentId;
//getter and setter methods
}
```
Teacher.java
```
public class Teacher extends Person {
private String teacherId;
public void teach() {
System.out.println("I am teaching.");
}
//getter and setter methods
}
```
Test01.java
```
public class Test01 {
public static void main(String[] args) {
Student1 student = new Student1();
student.setName("Tom");
student.setGender("Male");
student.setStudentId("S0001");
Teacher teacher = new Teacher();
teacher.setName("Linda");
teacher.setGender("Female");
teacher.setTeacherId("T0001");
System.out.println("Student: " + student.getName() + ", " + student.getGender() + ", " + student.getStudentId());
student.eat();
student.sleep();
System.out.println("Teacher: " + teacher.getName() + ", " + teacher.getGender() + ", " + teacher.getTeacherId());
teacher.eat();
teacher.sleep();
teacher.teach();
}
}
```
运行Test01.java的main方法,输出结果为:
```
Student: Tom, Male, S0001
I am eating.
I am sleeping.
Teacher: Linda, Female, T0001
I am eating.
I am sleeping.
I am teaching.
```
可以看到,Student1类和Teacher类都成功继承了Person类的成员,包括属性和方法。
阅读全文