【发布时间】:2011-10-30 00:09:08
【问题描述】:
我知道在父类中有一个受保护的变量是不好的设计,因为所有子类都可以更改该值。但是,我试图对其进行测试,但我在这里做错了。它告诉我在卡车类中找不到符号speed = 999999;。我以为子类可以访问父类中的受保护变量speed。
public class Vehicle {
protected double speed;
protected double maxSpeed;
public Vehicle(double speed, double maxSpeedIn) throws InvalidDataException{
setSpeed(speed);
maxSpeed = maxSpeedIn;
}
public void setSpeed(double s) throws InvalidDataException {
if (s < 0.0) {
throw new InvalidDataException("Negative speed is not valid" );
}
if (s > maxSpeed) {
throw new InvalidDataException("Speed cannot exceed maximum spped:");
}
speed = s;
}
}
public class Truck extends Vehicle {
public Truck(double speedin, double maxSpeedin) throws InvalidDataException {
super(speedin,maxSpeedin);
}
speed = 999999;
}
【问题讨论】:
标签: java inheritance protected