用Java实现问题描述 住宿学生信息包括:学号、姓名、性别、年龄、班级、用电量、用水量 等信息。教工信息包括职工号、姓名、性别、年龄、工作部门、用电量、用水量等信息。 能计算出学生和教工每月所要交的电费和水费。定义一个人员类,实现学生和教工共同的信 息和行为。
时间: 2023-10-20 14:03:59 浏览: 100
Java编写一个学生信息管理系统,实现学生信息包括:学号、姓名、性别、年龄、班级等信息
以下是用Java实现的代码:
```
class Person {
private String id; // 学号或职工号
private String name;
private String gender;
private int age;
private double electricityUsage; // 用电量
private double waterUsage; // 用水量
public Person(String id, String name, String gender, int age, double electricityUsage, double waterUsage) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.electricityUsage = electricityUsage;
this.waterUsage = waterUsage;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
public double getElectricityUsage() {
return electricityUsage;
}
public double getWaterUsage() {
return waterUsage;
}
public double calculateElectricityFee(double rate) {
return electricityUsage * rate;
}
public double calculateWaterFee(double rate) {
return waterUsage * rate;
}
}
class Student extends Person {
private String className;
public Student(String id, String name, String gender, int age, double electricityUsage, double waterUsage, String className) {
super(id, name, gender, age, electricityUsage, waterUsage);
this.className = className;
}
public String getClassName() {
return className;
}
}
class Teacher extends Person {
private String department;
public Teacher(String id, String name, String gender, int age, double electricityUsage, double waterUsage, String department) {
super(id, name, gender, age, electricityUsage, waterUsage);
this.department = department;
}
public String getDepartment() {
return department;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("2018001", "张三", "男", 20, 100.0, 50.0, "计算机科学与技术");
Teacher t = new Teacher("10001", "李四", "女", 35, 200.0, 100.0, "计算机科学与技术");
double electricityRate = 1.0; // 电费单价
double waterRate = 2.0; // 水费单价
System.out.println(s.getName() + "的月电费为:" + s.calculateElectricityFee(electricityRate));
System.out.println(s.getName() + "的月水费为:" + s.calculateWaterFee(waterRate));
System.out.println(t.getName() + "的月电费为:" + t.calculateElectricityFee(electricityRate));
System.out.println(t.getName() + "的月水费为:" + t.calculateWaterFee(waterRate));
}
}
```
在上面的代码中,我们定义了一个 `Person` 类作为学生和教工的基类,包含了学号/职工号、姓名、性别、年龄、用电量和用水量等信息,以及计算电费和水费的方法。然后我们又定义了两个子类 `Student` 和 `Teacher`,分别继承了 `Person` 类,并增加了班级和工作部门的属性。
在主函数中,我们创建了一个学生对象 `s` 和一个教工对象 `t`,并分别计算出他们的月电费和月水费。在实际应用中,我们可以根据业务需求,设置不同的电费单价和水费单价,从而计算出每个人员的具体费用。
阅读全文