Sasank Sunkavalli
Sasank Sunkavalli

Reputation: 3964

Can a subclass access parent class private members if both the classes are in the same package

I am reading a Java Doc , which says

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members

It says a Subclass can access the Parent's class private members if they are in the same package. I have tried it , I am unable to access the Private member of the parent Class in Subclass

Upvotes: 1

Views: 669

Answers (2)

Pronoy999
Pronoy999

Reputation: 660

There is a difference between package-private and private members. Private members can't be accessed by anyone other than the class itself. But Package private members are those members who are private to that particular package only and they can be accessed by any member within that particular package.

enter image description here

Upvotes: 1

luk2302
luk2302

Reputation: 57114

No, it states

If the subclass is in the same package as its parent, it also inherits the package-private members of the parent

package-private (no modifier) is not the same thing as private (private modifier). See https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html for the differences.

Upvotes: 4

Related Questions