Home > Article > Backend Development > Why can subclasses access private methods of parent class?
<code>class PrivateOverride { private void f() { System.out.println("private f()"); } public void hello(){ this.f(); this.bar(); } protected void bar(){ System.out.print("pri bar"); } } class Derived extends PrivateOverride { public void f() { System.out.println("public f()"); } public void bar(){ System.out.print("deri bar"); } } class Test4{ public static void main(String[] args) { Derived po = new Derived(); po.hello(); } }</code>
Output:
private f()
deri bar
Why
<code>class PrivateOverride { private void f() { System.out.println("private f()"); } public void hello(){ this.f(); this.bar(); } protected void bar(){ System.out.print("pri bar"); } } class Derived extends PrivateOverride { public void f() { System.out.println("public f()"); } public void bar(){ System.out.print("deri bar"); } } class Test4{ public static void main(String[] args) { Derived po = new Derived(); po.hello(); } }</code>
Output:
private f()
deri bar
Why
First of all, this is not a direct call to the f()
method of private
, just like the getter
method can get the private
instance variable. This needs no explanation.
There is an inheritance problem here: the f method
in the Derived
class is not an override of the PrivateOverride f method
of its parent class, because the overridden method requires that the access permission modifier of the overridden method cannot be higher than the parent class’s PrivateOverride f method
The class is more strict. When executing this.f()
in the hello method, the compiler gives priority to finding the
nearest f (that is, the
f
of the parent class), so
private f()
You are accessing private methods through public methods, this is okay
It is a private method that allows calling this class
According to your above example, it does not mean that the subclass can access the private method of the parent class. Because
hello
If the subclass is like this:
<code>class Derived extends PrivateOverride { public void hello() { System.out.println("public f()"); } public void bar(){ this.f(); //... } }</code>🎜If it can run normally, it means that the subclass can access the private method of the parent class. 🎜