简体   繁体   中英

Child class Changing a protected variable from a Parent class in Java

I know that it is bad design to have a protected variable in a parent class because all child classes can change that value. However, I was trying to test it out but I am doing something wrong here. It's telling me that cannot find symbol speed = 999999; in Truck class. I thought the child class has access to the protected variable speed in parent class.

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;

}

Your speed = 99999; line isn't valid the way you placed it in the Truck class. Try to put it somewhere else.

You could for example, just for your testing purpose, put it inside Truck 's constructor, after the call to super .

Note that you'd have had the exact same error if you had chosen another name altogher, like this:

public Truck extends Vehicle {

    public Truck(double speedin, double maxSpeedin) throws InvalidDataException {
        super(speedin,maxSpeedin);
    }

    justTesting = 999999;

}

In Java you cannot simply write instructions (like speed = 999999; ) in the middle of a class. Instructions must be written inside a method (function). What actually did you mean? When do you want this instruction to be carried out?

By the way, when setSpeed is called by the Vehicle constructor maxSpeed is not yet initialised, which will cause an error when you try to compare s and maxSpeed .

您正在尝试访问方法体外部的变量,它需要位于子类的构造函数或方法中,以便您以所需的方式访问它。

In my opinion protected variables doesn't have to be a bad thing. In some cases it really can be a necessity. But it depends on the design of course :)

In this case I think it makes perfect sense. And you should be able to change the speed value in the Truck class. The problem here is (probably) that the line speed = 999999; isn't placed inside a method in the class. I might be wrong, but it would seem to me Java compiles it as code unrelated to the class, and thus the speed variable cannot be found. Try putting it in the constructor and see what happens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM