定义一个人员类CPerson,包括字段:姓名,编号、性别,以及用于输入/输出的方法。在此基础上派生出学生类CStudent(增加“成绩”字段)和教师类(增加“教龄:字段),并实现对学生和教师信息的输入
时间: 2024-10-20 12:14:31 浏览: 83
在Java中,我们可以创建一个名为`CPerson`的基类,然后分别派生出`CStudent`和`CTeacher`两个子类,每个子类都会继承基类的共同属性,并添加各自的特有属性。以下是定义和操作这些类的示例:
```java
// 基类 CPerson
public class CPerson {
private String name;
private String id;
private char gender;
// 构造函数
public CPerson(String name, String id, char gender) {
this.name = name;
this.id = id;
this.gender = gender;
}
// 输入方法
public void inputInfo() {
System.out.println("请输入人员基本信息:");
System.out.print("姓名:");
Scanner scanner = new Scanner(System.in);
name = scanner.nextLine();
System.out.print("编号:");
id = scanner.nextLine();
System.out.print("性别(M/F):");
gender = scanner.next().charAt(0);
scanner.close();
}
// 输出方法
public void outputInfo() {
System.out.printf("姓名:%s, 编号:%s, 性别:%c\n", name, id, gender);
}
}
// 子类 CStudent
public class CStudent extends CPerson {
private double grade;
public CStudent(String name, String id, char gender, double grade) {
super(name, id, gender);
this.grade = grade;
}
@Override
// 输入方法,增加成绩字段的输入
public void inputInfo() {
super.inputInfo();
System.out.print("成绩:");
Scanner scanner = new Scanner(System.in);
grade = scanner.nextDouble();
scanner.close();
}
// 输出方法,包含成绩
public void outputInfo() {
super.outputInfo();
System.out.println("成绩:" + grade);
}
}
// 子类 CTeacher
public class CTeacher extends CPerson {
private int teachingYears;
public CTeacher(String name, String id, char gender, int teachingYears) {
super(name, id, gender);
this.teachingYears = teachingYears;
}
@Override
// 输入方法,增加教龄字段的输入
public void inputInfo() {
super.inputInfo();
System.out.print("教龄:");
Scanner scanner = new Scanner(System.in);
teachingYears = scanner.nextInt();
scanner.close();
}
// 输出方法,包含教龄
public void outputInfo() {
super.outputInfo();
System.out.println("教龄:" + teachingYears + "年");
}
}
// 主函数示例
public static void main(String[] args) {
CStudent student = new CStudent("", "", ' ', 0);
student.inputInfo();
student.outputInfo();
CTeacher teacher = new CTeacher("", "", ' ', 0);
teacher.inputInfo();
teacher.outputInfo();
}
```
阅读全文