abstract class Express{ public int weight; public abstract int getWeight(); public abstract int getTotal(); } public class SLExpress extends Express{ public int cost; public SLExpress(){ } public SLExpress(int weight){ super.weight=weight; } public int getTotal(int weight){ cost=12+(weight-1)*2; return cost; } } public class DDExpress extends Express{ public int cost; public DDExpress(){ } public DDExpress(int weight){ super.weight=weight; } public int getTotal(int weight){ cost=5+weight-1; return cost; } } public class CaicaiStation{ public int sum; public int calculate(Express[] ex){ for(int i=0;i<ex.length;i++){ sum+=ex[i]; } } }纠错
时间: 2024-03-09 21:49:45 浏览: 47
c++实验8-继承与派生上机练习题.doc
在这段代码中,有一些错误:
1. 在抽象类`Express`中定义了抽象方法`getWeight()`和`getTotal()`,但在其子类中未对其进行实现,需要在子类中实现这两个方法。
2. `public int getTotal(int weight)`在子类中的实现与抽象类中定义的方法名`public abstract int getTotal()`不同,应该与抽象类中定义的方法名保持一致。
3. 在子类中的构造函数中,应该调用`super()`来调用父类的构造函数,而不是直接赋值。
4. 在`CaicaiStation`类中`calculate()`方法中,对`sum`变量进行累加时,应该加上`ex[i].getTotal()`,因为`Express`类中并没有定义`sum`属性。
下面是修改后的代码:
```
abstract class Express {
public int weight;
public abstract int getWeight();
public abstract int getTotal();
}
public class SLExpress extends Express {
public int cost;
public SLExpress() {
}
public SLExpress(int weight) {
super.weight = weight;
}
public int getWeight() {
return weight;
}
public int getTotal() {
cost = 12 + (weight - 1) * 2;
return cost;
}
}
public class DDExpress extends Express {
public int cost;
public DDExpress() {
}
public DDExpress(int weight) {
super.weight = weight;
}
public int getWeight() {
return weight;
}
public int getTotal() {
cost = 5 + weight - 1;
return cost;
}
}
public class CaicaiStation {
public int sum;
public int calculate(Express[] ex) {
for (int i = 0; i < ex.length; i++) {
sum += ex[i].getTotal();
}
return sum;
}
}
```
阅读全文