所以我需要为容器类实现一个getCurrentVolumeInCCs方法,但是我对如何实现它有点困惑。此外,我在Glass和Cup类中获得了正确的音量值,但是当我调用Vessel类中的任何其他方法时,这些值都不会被结转。我猜它是因为它们存储在子类中而不能在基类中使用,我是对的吗?
船只类(摘要)
package containers;
public abstract class Vessel {
private double volume;
private double currentVolume;
public Vessel() {
volume = 0;
currentVolume = 0;
}
abstract double getVolumeInCC();
public double getCurrentContents() {
return currentVolume;
}
public double drink(double amountToDrink) {
double volumeLeft;
System.out.println("you drank " + amountToDrink + " CCs");
volumeLeft = volume - amountToDrink;
return volumeLeft;
}
public double fill(double amountPoured) {
double volumeAdded = amountPoured;
double volumeSpilled = 0;
System.out.println("you poured " + amountPoured + " CCs");
if(volumeAdded > volume) {
volumeSpilled = amountPoured - volume;
System.out.println("you spilled " + volumeSpilled);
}
return volumeAdded;
}
}
玻璃类
package containers;
public class Glass extends Vessel{
private double volume;
private double radiusBase;
private double height;
public Glass() {}
public Glass(double r, double h) {
this.radiusBase = r;
this.height = h;
}
@Override
double getVolumeInCC() {
volume = (Math.PI)*(Math.pow(radiusBase, 2))*height;
return volume;
}
}
杯赛类
package containers;
public class Cup extends Vessel {
private double volume;
private double radiusLip;
public Cup(double r) {
volume = 0;
this.radiusLip = r;
}
@Override
double getVolumeInCC() {
volume = (0.5)*(Math.PI)*(Math.pow(radiusLip, 3))*(4/3);
return volume;
}
}
答案 0 :(得分:2)
您在子类中volume
隐藏Vessel
,因为它是private
字段。我相信你想在volume
中保护currentVolume
和Vessel
,
protected double volume;
protected double currentVolume;
此外,您应该从子类中删除private double volume
(这样您就不会影响他们现在从Vessel
继承的字段。)