我知道,在父類中有一個受保護的變量是個不好的設計,因爲所有子類都可以更改該值。但是,我試圖測試它,但我在這裏做錯了什麼。它告訴我,在Truck類中找不到符號speed = 999999;
。我認爲子類可以訪問父類中的受保護變量speed
。子類從Java中的父類中更改受保護的變量
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;
}
現在就工作,謝謝! – Dan