prog
prog

Reputation: 150

Cross-package inheritance with package access right (default access right)

So I have a class named Vehicle that is in package A and I have a class named Car in package B. Class Car extends Vehicle, so it inherits certain elements from Vehicle. My question is what does Car inherit?

I think it inherits all the public methods and variable, but in my assignment I have variables with package access right (not public, not private), so I must re-declare all the variables from Vehicle in Car, right? Also, what is not clear is if we can compare Car and Vehicle objects using the equals() method, since the variables are not the same even if they have the same name. Also, how come I have to re-declare all the variables even though I use super() in the constructor Car? Aren't the variables initiated in Vehicle? Also, since I must re-declare all the variables from Vehicle, are all the public methods I inherit from Vehicle, completely useless? What's the point of inheriting from a class that only has package access right variables?

Upvotes: 3

Views: 1576

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

You got it wrong. It inherits everything from the Vehicle class. The package-protected elements are not accessible from the subclass, that's all. So you can't access these fields and methods, and you can't override them either. But that doesn't mean you need to redeclare them.

Let's take an example. Suppose you design a Vehicle class, and allow for subclasses to override and have access to the color of the vehicle. But suppose you don't want the subclasses to mess with the engine of the vehicle. You would thus have something like this:

public class Vehicle {
    private Engine engine;
    protected Color color = Color.BLACK;

    public Vehicle() {
        this.engine = new Engine();
    }

    public final void start() {
        System.out.println("starting engine...");
        engine.start();
        System.out.println("engine started");
    }

    public final Color getColor() {
        return this.color;
    }
}

public class Car extends Vehicle {

    public Car(Color color) {
        super();
        this.color = color;
    }
}

A Car is a Vehicle. So since you can start a vehicle, you can also start a car. And since a vehicle has an engine, a car also has one. It's not possible from inside the Car class to modify or do anything with the engine because it's private to the Vehicle class, but a car has one.

The color field, however, is protected. This means that the Car class can have access to this field. For example, it modifies it in the constructor, in order to be able to have another color than Black.

Try the following code:

Car car = new Car();
car.start();

And you'll see that the engine gets started.

Upvotes: 1

Related Questions