If the superclass data members are made private,
they cannot be accessed directly in the subclass.
Understanding the Original Code:
In the superclass Vehicle, the data members were:
protected String colour;
protected String registration;
Since they are declared as protected,
the subclass Car can access them directly.
What Happens if They Become Private?
private String colour;
private String registration;
Private members are accessible only inside the same class.
class Vehicle
{
private String colour;
}
Therefore, subclass Car cannot directly access:
colour
registration
Result:
-
Direct access to superclass data members from subclass
becomes impossible.
-
Compilation error may occur if subclass tries to access them directly.
Example of Invalid Access:
class Car extends Vehicle
{
public void show()
{
System.out.println(colour); // ERROR
}
}
Here, colour is private in the superclass,
so it cannot be accessed directly in the child class.
Error Produced:
colour has private access in Vehicle
How to Access Private Members?
Private members can still be accessed indirectly using:
- Getter methods
- Setter methods
- Public/protected methods
Example Using Getter Method:
class Vehicle
{
private String colour;
public String getColour()
{
return colour;
}
}
class Car extends Vehicle
{
public void show()
{
System.out.println(getColour());
}
}
Difference Between protected and private:
| Access Modifier |
Accessible in Subclass? |
| protected |
Yes ✅ |
| private |
No ❌ |
Important Concept:
protected → Accessible in subclass
private → Accessible only within same class
Final Conclusion:
If the superclass data members are changed from
protected to private:
-
The subclass cannot access them directly.
-
Compilation error may occur.
-
Getter/Setter methods must be used for access.