Home > Back-end >  Why subclasses inherit private fields?
Why subclasses inherit private fields?

Time:11-26

I'm creating a new class which is vehicle. I'm expecting the only protected variables inherit to subclasses. But when I try to create Constructor with IDE, it is also using superclasses private variables? -Which is private String vehicleName- I'm not clearly understanding this situation. Shouldn't I use auto Concstructor?

public class Vehicle {
    protected int capacityOfPassengers;
    protected String mapOfRoute;
    private String vehicleName;

    public Vehicle(int capacityOfPassengers, String mapOfRoute, 
                   String vehicleName) {

        this.capacityOfPassengers = capacityOfPassengers;
        this.mapOfRoute = mapOfRoute;
        this.vehicleName = vehicleName;
    }
}

public class LandVehicle extends Vehicle {
    private String brand;
    private int priceModel;

    public LandVehicle(int capacityOfPassengers, String mapOfRoute, 
                       String vehicleName, String brand, int priceModel) {

        super(capacityOfPassengers, mapOfRoute, vehicleName);
        this.brand = brand;
        this.priceModel = priceModel;
    }
}

CodePudding user response:

You cannot access vehicleName from LandVehicle. You just pass some string parameter to super constructor, and the super constructor sets the vehicleName. For example, you can't initialize this field inside LandVehicle class as this.vehicleName = vehicleName.

CodePudding user response:

Generally, a class has a default constructor, taking no arguments, IF no constructor has been provided by you.

When you subclass Vehicle with your LandVehicle, your LandVehicle is a type of Vehicle. This means that it inherits methods and field from its superclass, even if they are private. For the class LandVehicle these members are just not visible, but they are still present - otherwise it couldn't function properly. The private keyword is an access modifier, that changes visibility to the caller.

As a result, to instantiate a LandVehicle, you also must provide the required attributes of its superclass Vehicle (since there is no default, no-arg constructor in Vehicle). In your example, a LandVehicle without a name (from Vehicle) wouldn't make sense, since a LandVehicle is a Vehicle, which requires a name.

  • Related