简体   繁体   中英

How do I override `toString` in my derived class and use the private instance variables from the base class?

This is my base class Vehicle with private instance variables.

public class Vehicle {
    private int numPassengers;
    private String colour;

    Vehicle(int passengers, String colour) {
        this.numPassengers = passengers;
        this.colour = colour;
    }

    public String toString() {
        return colour + " " + numPassengers + " passengers";
    }
}

Note that there are no accessor methods in this class and that I cannot edit this class in any way.

I have a derived class Car with one additional instance variable numberOfDoors

public class Car extends Vehicle
{   
    private int numberOfDoors;

    public Car(String newColour, int newNumberOfPassengers, int newNumberOfDoors)
    {
        super(newNumberOfPassengers, newColour);
        this.numberOfDoors = newNumberOfDoors;
    }

    @Override
    public String toString()
    {
        return colour + " " + numPassengers + " passengers " + numberOfDoors + " doors";
    }
}

I can edit this class as I desire and I am aware of the different constructor method signature.

Obviously, the return statement in toString() is giving me issues because this class has no access to the private instance variable in Vehicle . I know that if the instance variables in Vehicle has package/protected access, this wouldn't be an issue, but either my instructor has made a mistake or we are supposed to come up with a workaround.

Is there a way around this that I'm missing?

The sub-class can't access the private members of the super-class, unless you have getters for them.

What you could you is :

@Override
public String toString()
{
    return super.toString() + " " + numberOfDoors + " doors";
}

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