定义一个Person类,含:姓名、性别、年龄等字段;继承Person类设计Teacher类,增加:职称、部门等字段;继承Person类设计 Student类,增加:学号、班级等字段。定义各类的构造方法和 toString(方法,并分别创建对象进行测试。用Java语言进行编写
时间: 2024-11-22 07:42:59 浏览: 2
关于java中的类
在Java中,我们可以按照这样的结构来定义和实现这个需求:
```java
// 定义 Person 类作为父类
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 +
'}';
}
}
// 继承 Person 类的 Teacher 类
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 "Teacher{" +
"super." + super.toString() + // 使用父类的 toString 输出 +
", title='" + title + '\'' +
", department='" + department + '\'' +
'}';
}
}
// 继承 Person 类的 Student 类
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;
}
// toString 方法
@Override
public String toString() {
return "Student{" +
"super." + super.toString() + // 使用父类的 toString 输出 +
", studentId='" + studentId + '\'' +
", className='" + className + '\'' +
'}';
}
}
// 测试部分
public class Main {
public static void main(String[] args) {
// 创建 Person 对象
Person person = new Person("张三", "男", 30);
System.out.println(person);
// 创建 Teacher 对象
Teacher teacher = new Teacher("李四", "女", 35, "教授", "数学系");
System.out.println(teacher);
// 创建 Student 对象
Student student = new Student("王五", "男", 20, "1001", "一班");
System.out.println(student);
}
}
```
运行上述代码,会打印出每个对象的详细信息。
阅读全文