用Java语言写定义一个Person类,含:姓名、性别、年龄等字段;继承Person类设计Teacher类,增加:职称、部门等字段;继承Person类设计Student类,增加:学号、班级等字段。定义各类的构造方法和toString()方法,并分别创建对象进行测试。
时间: 2024-02-28 22:54:41 浏览: 134
好的,以下是使用Java语言实现上述需求的代码:
```java
// Person类
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;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
'}';
}
}
// Teacher类
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;
}
public String getTitle() {
return title;
}
public String getDepartment() {
return department;
}
@Override
public String toString() {
return "Teacher{" +
"title='" + title + '\'' +
", department='" + department + '\'' +
"} " + super.toString();
}
}
// Student类
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;
}
public String getStudentId() {
return studentId;
}
public String getClassName() {
return className;
}
@Override
public String toString() {
return "Student{" +
"studentId='" + studentId + '\'' +
", className='" + className + '\'' +
"} " + super.toString();
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
Person person = new Person("张三", "男", 20);
System.out.println(person);
Teacher teacher = new Teacher("李四", "女", 30, "教授", "计算机系");
System.out.println(teacher);
Student student = new Student("王五", "男", 19, "20210001", "软件工程1班");
System.out.println(student);
}
}
```
运行结果如下:
```
Person{name='张三', gender='男', age=20}
Teacher{title='教授', department='计算机系'} Person{name='李四', gender='女', age=30}
Student{studentId='20210001', className='软件工程1班'} Person{name='王五', gender='男', age=19}
```
阅读全文