定义一个Person类,含:姓名、性别、年龄等字段;设计Teacher类继承Person类,增加:职称、部门等字段;设计Student类继承Person类,增加:学号、班级等字段。定义各类的构造方法和toString()方法,并分别创建对象进行测试。
时间: 2024-10-09 11:06:00 浏览: 97
设计一个人类person,包括人员编号和姓名等数据成员以及相关的成员函数
在Java中,你可以按照以下步骤定义这些类:
```java
// 定义 Person 类
public class Person {
private String name;
private String gender;
private int age;
// 默认构造器
public Person() {}
// 具体构造器接受参数
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
// toString 方法返回个人信息字符串
@Override
public String toString() {
return "Name: " + name + ", Gender: " + gender + ", Age: " + age;
}
}
// Teacher 类继承自 Person 类并添加新字段和构造器
public class Teacher extends Person {
private String title;
private String department;
// Teacher 类的构造器
public Teacher(String name, String gender, int age, String title, String department) {
super(name, gender, age); // 调用父类的构造器
this.title = title;
this.department = department;
}
// toString 方法扩展父类的方法
@Override
public String toString() {
return super.toString() + ", Title: " + title + ", Department: " + department;
}
}
// Student 类同样继承自 Person 类并添加新字段和构造器
public class Student extends Person {
private String studentID;
private String className;
// Student 类的构造器
public Student(String name, String gender, int age, String studentID, String className) {
super(name, gender, age);
this.studentID = studentID;
this.className = className;
}
// toString 方法扩展父类的方法
@Override
public String toString() {
return super.toString() + ", Student ID: " + studentID + ", Class: " + className;
}
}
```
现在你可以使用这些类来创建对象并调用 `toString` 方法进行测试:
```java
public static void main(String[] args) {
// 创建一个 Teacher 对象
Teacher teacher = new Teacher("John Doe", "Male", 35, "Professor", "Mathematics");
// 创建一个 Student 对象
Student student = new Student("Jane Smith", "Female", 18, "1001", "Science 1A");
// 打印他们的信息
System.out.println(teacher);
System.out.println(student);
}
```
阅读全文