java编写一个学生和教师数据输入的显示程序,学生数据有编号,姓名,班号和成绩 教师数据有编号姓名职称和部门要求将编号姓名输入 显示设计成一个类person,并作为学生数据操作类Student和教师数据操作类Teacher的父类
时间: 2024-11-14 19:20:29 浏览: 52
在Java中,你可以创建一个名为`Person`的通用类作为所有员工(包括学生和教师)的基础类,然后分别创建`Student`和`Teacher`类作为`Person`的子类。首先,我们定义`Person`类,它包含基本的标识信息:
```java
public class Person {
private String id;
private String name;
// 构造函数
public Person(String id, String name) {
this.id = id;
this.name = name;
}
// 获取和设置方法
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 打印方法,用于显示数据
@Override
public String toString() {
return "ID: " + id + ", Name: " + name;
}
}
```
接着,创建`Student`和`Teacher`类,它们继承自`Person`并添加特定属性:
```java
public class Student extends Person {
private int studentNumber;
private int grade;
public Student(String id, String name, int studentNumber, int grade) {
super(id, name);
this.studentNumber = studentNumber;
this.grade = grade;
}
// 学生特有的获取和设置方法
public int getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(int studentNumber) {
this.studentNumber = studentNumber;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
// 重写toString方法展示更多细节
@Override
public String toString() {
return super.toString() + ", Student Number: " + studentNumber + ", Grade: " + grade;
}
}
public class Teacher extends Person {
private String title;
private String department;
public Teacher(String id, String name, String title, String department) {
super(id, name);
this.title = title;
this.department = department;
}
// 教师特有的获取和设置方法
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
// 重写toString方法展示更多细节
@Override
public String toString() {
return super.toString() + ", Title: " + title + ", Department: " + department;
}
}
```
最后,你可以创建主程序来接收用户输入,实例化相应的类,并打印数据:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Student details (or 't' for teacher):");
String input = scanner.next();
if ("t".equals(input)) {
System.out.print("ID: ");
String id = scanner.next();
System.out.print("Name: ");
String name = scanner.next();
Teacher teacher = new Teacher(id, name, "", "");
System.out.println(teacher);
} else {
System.out.print("ID: ");
String id = scanner.next();
System.out.print("Name: ");
String name = scanner.next();
System.out.print("Student Number: ");
int studentNumber = scanner.nextInt();
System.out.print("Grade: ");
int grade = scanner.nextInt();
Student student = new Student(id, name, studentNumber, grade);
System.out.println(student);
}
scanner.close();
}
}
```
当你运行这个程序,用户可以选择输入学生或教师的信息,程序会根据选择创建并显示相应对象的内容。
阅读全文