![](/img/trans.png)
[英]How to initialize a protected final variable in a child class of an abstract parent in Java?
[英]Child class Changing a protected variable from a Parent class in Java
我知道在父类中拥有受保护的变量是不好的设计,因为所有子类都可以更改该值。 但是,我试图测试它,但我在这里做错了。 它告诉我找不到符号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;
}
你的速度= 99999; line放在Truck类中的方式无效。 试着把它放在其他地方。
例如,您可以在调用super之后将其放入Truck的构造函数中,仅用于测试目的。
请注意,如果您选择了另一个名称altogher,则会遇到完全相同的错误,如下所示:
public Truck extends Vehicle {
public Truck(double speedin, double maxSpeedin) throws InvalidDataException {
super(speedin,maxSpeedin);
}
justTesting = 999999;
}
在Java中,您不能简单地在类的中间编写指令(如speed = 999999;
)。 必须在方法(函数)中写入指令。 你究竟是什么意思? 你什么时候想要执行这个指令?
顺便说一下,当Vehicle
构造函数maxSpeed
时, setSpeed
尚未初始化,这会在您尝试比较s
和maxSpeed
时导致错误。
您正在尝试访问方法体外部的变量,它需要位于子类的构造函数或方法中,以便您以所需的方式访问它。
在我看来,受保护的变量不一定是坏事。 在某些情况下,它确实是必要的。 但这取决于当然的设计:)
在这种情况下,我认为这是完全合理的。 您应该能够更改Truck类中的speed
值。 这里的问题是(可能)线speed = 999999;
不是放在类中的方法内。 我可能错了,但在我看来,Java会将其编译为与类无关的代码,因此无法找到速度变量。 尝试将它放在构造函数中,看看会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.