定义一个Person类,含:姓名、性别、年龄等字段;继承Person类设计Teacher类,增加:职称、部门等字段;继承Person类设计 Student类,增加:学号、班级等字段。定义各类的构造方法和toString()方法,并分别创建对象进行测试。
时间: 2024-10-15 10:13:45 浏览: 29
设计一个人类person,包括人员编号和姓名等数据成员以及相关的成员函数
首先,我们定义一个基础的`Person`类,包含姓名、性别和年龄字段:
```java
public class Person {
private String name;
private String gender;
private int age;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
// toString()方法用于获取Person对象的简单描述
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
'}';
}
}
```
然后,我们设计`Teacher`类,它继承自`Person`并添加了职称和部门字段:
```java
public class Teacher extends Person {
private String title;
private String department;
public Teacher(String name, String gender, int age, String title, String department) {
super(name, gender, age);
this.title = title;
this.department = department;
}
@Override
public String toString() {
return "Teacher{" +
super.toString() +
", title='" + title + '\'' +
", department='" + department + '\'' +
'}';
}
}
```
接着,我们设计`Student`类,同样继承自`Person`并增加了学号和班级字段:
```java
public class Student extends Person {
private String studentId;
private String className;
public Student(String name, String gender, int age, String studentId, String className) {
super(name, gender, age);
this.studentId = studentId;
this.className = className;
}
@Override
public String toString() {
return "Student{" +
super.toString() +
", studentId='" + studentId + '\'' +
", className='" + className + '\'' +
'}';
}
}
```
现在我们可以创建这些类的对象进行测试:
```java
public static void main(String[] args) {
Person person = new Person("John", "Male", 30);
System.out.println(person);
Teacher teacher = new Teacher("Jane", "Female", 45, "Professor", "Math Department");
System.out.println(teacher);
Student student = new Student("Alice", "Female", 18, "12345", "Class A");
System.out.println(student);
}
```
运行这段代码,你会看到每个对象的详细信息。
阅读全文