书中问题:编写一个模拟可充电电池的类 Battery。电池有一个构造函数 public Battery(double capacity) ,其中容量是以毫安时为单位的值。典型的 AA 电池容量为 2000 至 3000 mAh。public void drain(double amount) 方法将电池的容量消耗给定量。public void charge() 方法将电池充电至其原始容量。public double getRemainingCapacity() 方法获取电池的剩余容量。
我的问题:我的实例变量对吗?您如何确定私有实例变量中需要包含什么?(如果这是有道理的)这段代码可以用更好的方式编写吗?
我的代码:
public class Battery
{
private double fullCharge;
private double batteryCapacity;
public Battery(double capacity)
{
batteryCapacity = capacity;
fullCharge = capacity;
}
public void drain(double amount)
{
batteryCapacity = batteryCapacity - amount;
}
public void charge()
{
batteryCapacity = fullCharge;
}
public double getRemainingCapacity()
{
return batteryCapacity;
}
}