In Java,protected memberscan only be accessedwithin the same packageor bysubclasses, but there is a key restriction:
A protected member of a superclass is only accessible through inheritance in a subclass but not through an instance of the superclass that is declared outside the package.
Why does compilation fail?
In the MiniVan class, the following line causes acompilation error:
java
Car car = new Car();
car.brand = "Peugeot 807";
The brand field isprotectedin Car, which means it isnot accessible via an instance of Car outside the vehicule.parent package.
Even though MiniVan extends Car, itcannotaccess brand using a Car instance (car.brand) because car is declared as an instance of Car, not MiniVan.
The correct way to access brand inside MiniVan is through inheritance (this.brand or super.brand).
Corrected Code
If we change the MiniVan class like this, it will compile and run successfully:
java
package vehicule.child;
import vehicule.parent.Car;
public class MiniVan extends Car {
public static void main(String[] args) {
MiniVan minivan = new MiniVan(); // Access via inheritance
minivan.brand = "Peugeot 807";
System.out.println(minivan.brand);
}
}
This would output:
nginx
Peugeot 807
Key Rule from Oracle Java Documentation
Protected membersof a class are accessible withinthe same packageand tosubclasses, butonly through inheritance, not through a superclass instance declared outside the package.
References:
Java SE 21 & JDK 21 - Controlling Access to Members of a Class
Java SE 21 & JDK 21 - Inheritance Rules