用Java,最终成员变量和抽象方法为一个JAVA州立大学的学生建立账单系统,州内外的学生收费不同,州内每学分收费
时间: 2023-11-10 18:05:05 浏览: 87
可以先定义一个抽象类`Student`,其中包含成员变量`name`、`id`、`credit`等属性,以及抽象方法`calculateTuition()`用于计算学费。具体代码如下:
```java
public abstract class Student {
protected String name;
protected String id;
protected int credit;
public Student(String name, String id, int credit) {
this.name = name;
this.id = id;
this.credit = credit;
}
public abstract double calculateTuition();
}
```
然后定义两个子类`InStateStudent`和`OutStateStudent`,分别代表州内和州外的学生。这两个子类继承自`Student`类,并且实现父类中的`calculateTuition()`方法。具体代码如下:
```java
public class InStateStudent extends Student {
private static final double IN_STATE_TUITION_RATE = 1000.0;
public InStateStudent(String name, String id, int credit) {
super(name, id, credit);
}
@Override
public double calculateTuition() {
return this.credit * IN_STATE_TUITION_RATE;
}
}
public class OutStateStudent extends Student {
private static final double OUT_STATE_TUITION_RATE = 1500.0;
public OutStateStudent(String name, String id, int credit) {
super(name, id, credit);
}
@Override
public double calculateTuition() {
return this.credit * OUT_STATE_TUITION_RATE;
}
}
```
这样,我们就可以根据不同的学生类型计算学费了。比如,对于一个州内学生,可以这样创建对象并计算学费:
```java
InStateStudent inStateStudent = new InStateStudent("Tom", "001", 15);
double tuition = inStateStudent.calculateTuition();
System.out.println("州内学生 " + inStateStudent.name + " 的学费为:" + tuition);
```
输出结果为:
```
州内学生 Tom 的学费为:15000.0
```
同理,对于一个州外学生,可以这样创建对象并计算学费:
```java
OutStateStudent outStateStudent = new OutStateStudent("Jerry", "002", 15);
double tuition = outStateStudent.calculateTuition();
System.out.println("州外学生 " + outStateStudent.name + " 的学费为:" + tuition);
```
输出结果为:
```
州外学生 Jerry 的学费为:22500.0
```
阅读全文