定义一个Person类,含姓名、性别、年龄、等字段;继承Person类设计Teacher类,增加职称、部门字段;继承Person类设计Student类,增加学号、入学时间、专业等字段。定义各类 的构造方法和toString方法,并分别创建对象进行测试。
时间: 2024-10-23 11:08:23 浏览: 32
首先,我们来定义一个基础的`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方法展示基本信息
@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;
}
// toString方法展示教师信息
@Override
public String toString() {
return super.toString() +
", title='" + title + '\'' +
", department='" + department + '\'';
}
}
```
接着,我们定义`Student`类作为`Person`的子类:
```java
public class Student extends Person {
private int studentId;
private Date enrollmentDate;
private String major;
// 构造方法,接收父类所有参数并初始化额外字段
public Student(String name, String gender, int age, int studentId, Date enrollmentDate, String major) {
super(name, gender, age);
this.studentId = studentId;
this.enrollmentDate = enrollmentDate;
this.major = major;
}
// toString方法展示学生信息
@Override
public String toString() {
return super.toString() +
", studentId=" + studentId +
", enrollmentDate=" + enrollmentDate +
", major='" + major + '\'';
}
}
```
现在可以创建这些类的对象并打印它们:
```java
public static void main(String[] args) {
Teacher teacher = new Teacher("张老师", "女", 35, "教授", "计算机系");
System.out.println(teacher);
Student student = new Student("小明", "男", 20, 20200101, "软件工程", "计算机科学与技术");
System.out.println(student);
}
```
运行这个程序,你会看到`Teacher`和`Student`类的对象的详细信息。
阅读全文