定义一个Person类,含姓名、性别、年龄等字段;继承Person类设计Teacher类,增加职称、部门等字段;继承Person类设计Student 类,增加学号、入学时间、专业等字段。定义各类的构造方法和toString0方法,并分别创建对象进行测试。
时间: 2023-06-07 18:11:49 浏览: 128
好的,很高兴能回答您的问题。以下是您所要求的定义Person、Teacher和Student类、各类的构造方法和toString()方法的示例代码:
```
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;
}
public String toString() {
return "Name: " + name + "\nGender: " + gender + "\nAge: " + age;
}
}
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;
}
public String toString() {
return super.toString() + "\nTitle: " + title + "\nDepartment: " + department;
}
}
class Student extends Person {
private int id;
private String major;
private String enrollmentDate;
public Student(String name, String gender, int age, int id, String major, String enrollmentDate) {
super(name, gender, age);
this.id = id;
this.major = major;
this.enrollmentDate = enrollmentDate;
}
public String toString() {
return super.toString() + "\nStudent ID: " + id + "\nMajor: " + major + "\nEnrollment Date: " + enrollmentDate;
}
}
// 创建对象并测试
Person person = new Person("张三", "男", 25);
System.out.println(person.toString());
Teacher teacher = new Teacher("李四", "女", 35, "教授", "计算机科学");
System.out.println(teacher.toString());
Student student = new Student("王五", "男", 20, 123456, "软件工程", "2021-09-01");
System.out.println(student.toString());
```
上述代码输出的结果如下:
```
Name: 张三
Gender: 男
Age: 25
Name: 李四
Gender: 女
Age: 35
Title: 教授
Department: 计算机科学
Name: 王五
Gender: 男
Age: 20
Student ID: 123456
Major: 软件工程
Enrollment Date: 2021-09-01
```
希望对您有所帮助!
阅读全文