A private method can't be overridden by sub-classes. If the sub-classes declare a method with the same signature as a private method in the parent class, the sub-class method doesn't override the super-class method.
When you call method d()
, if d()
is not overridden by the sub-class, the executed method is PrivateOverride
's d()
. When that method calls f()
, it sees the private f()
method defined in PrivateOverride
. Since that method is not overridden (as it can't be), it calls that method and not the f()
method of the sub-class.
If d()
is overridden, the d()
method of the sub-class DerivedWithD
is executed. When that method calls f()
, it calls the f()
method of DerivedWithD
.
If f()
is no longer private, the f()
method in the sub-classes now overrides the f()
method of the super-class, and therefore f()
of the sub-class is executed in both cases.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…