用Java的代码定义一个person类,包含姓名、性别、年龄等字段;继承person类,设计teacher类,增加:职称、部门等字段;继承person类设计Student类增加,学号、班级等字段,定义各类的构造方法和to String()方法,并分贝创建对象进行测试
时间: 2023-06-08 09:04:43 浏览: 593
好的,以下是用Java代码定义Person、Teacher和Student类的实现,并且包含构造方法和to String()方法:
```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;
}
public String toString() {
return "Name: " + name + ", Gender: " + gender + ", Age: " + age;
}
// Getters and Setters omitted for brevity
}
public class Teacher extends Person {
private String position;
private String department;
public Teacher(String name, String gender, int age, String position, String department) {
super(name, gender, age);
this.position = position;
this.department = department;
}
public String toString() {
return super.toString() + ", Position: " + position + ", Department: " + department;
}
// Getters and Setters omitted for brevity
}
public class Student extends Person {
private String studentNumber;
private String className;
public Student(String name, String gender, int age, String studentNumber, String className) {
super(name, gender, age);
this.studentNumber = studentNumber;
this.className = className;
}
public String toString() {
return super.toString() + ", Student Number: " + studentNumber + ", Class Name: " + className;
}
// Getters and Setters omitted for brevity
}
```
然后我们可以在main方法中创建Person、Teacher和Student类的对象并进行一些测试,例如:
```java
public static void main(String[] args) {
Person person = new Person("John Doe", "Male", 25);
System.out.println(person.toString());
Teacher teacher = new Teacher("Jane Smith", "Female", 35, "Associate Professor", "Computer Science");
System.out.println(teacher.toString());
Student student = new Student("Tom Lee", "Male", 18, "20210001", "Class A");
System.out.println(student.toString());
}
```
输出结果如下:
```
Name: John Doe, Gender: Male, Age: 25
Name: Jane Smith, Gender: Female, Age: 35, Position: Associate Professor, Department: Computer Science
Name: Tom Lee, Gender: Male, Age: 18, Student Number: 20210001, Class Name: Class A
```
阅读全文