Cross-package inheritance with package permissions (default permissions)
So I have a class named Vehicle that is in package A and I have a class named Car in package B. The class Car extends Vehicle, so it inherits certain elements from Vehicle. My question is, what does Car inherit?
I think it inherits all public methods and variable, but in my assignment I have variables with package access rights (not public, not private), so I have to re-declare all variables from Vehicle in Car, right? Also, it is unclear if it is possible to compare Car and Vehicle objects using the equals () method, since the variables are not the same even if they have the same name. Also, why do I need to re-declare all variables even though I am using super () in Car's constructor? Aren't the variables initiated in Vehicle? Also, since I have to re-declare all the variables with Vehicle, are all the public methods that I inherit from Vehicle completely useless? What's the point of inheriting from a class that only has the right package access variables?
source to share
You are wrong. It inherits everything from the Vehicle class. Items protected by a package are not accessible from the subclass, which is all. Thus, you cannot access these fields and methods, and you cannot override them. But that doesn't mean you need to update them.
Let's take an example. Suppose you have developed a Vehicle class and allow subclasses to be overridden and have access to the vehicle color. But suppose you don't want the subclasses to interact with the vehicle engine. Thus, you will 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 car. Since you can start a vehicle, you can also start a car. And since a car is equipped with an engine, it also has a car. It is not possible from within the Car class to modify or do anything with the engine, because it is private to the Vehicle class, but the car has one.
However, the field color
is protected. This means that the Car class can access this field. For example, he modifies it in the constructor to have a different color than black.
Try using the following code:
Car car = new Car();
car.start();
And you will see that the engine starts.
source to share