“overriding” private methods with upcasting call in java

南笙酒味 提交于 2019-11-27 08:28:06

问题


public class PrivateOverride {
    private void f() {
        System.out.println("PrivateOverride f()");
    }
    public static void main(String[] args) {
        PrivateOverride po = new DerivedWithOutD();
        po.d();// PrivateOverride f()

        PrivateOverride poD = new DerivedWithD();
        poD.d();//Derived f()
    }

    public void d() {
        f();
    }
}

class DerivedWithOutD extends PrivateOverride {
    public void f() {
        System.out.println("Derived f()");
    }
}
class DerivedWithD extends PrivateOverride {
    public void f() {
        System.out.println("Derived f()");
    }

    public void d() {
        f();
    }
}

As the codes above show, when DerivedWithOutD don't override the method d(), it calls the f() belong to PrivateOverride, is that because method f() of PrivateOverride can't be overrided?But the d() inherit from PrivateOverride should belong to DerivedWithOutD, why d() calls the private f()? And why DerivedWithD class seems do the override, And can call the public f()? Also ,when I change the f() of PrivateOverride to public , it all print Derived f(), It confuse me now !


回答1:


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.



来源:https://stackoverflow.com/questions/37809153/overriding-private-methods-with-upcasting-call-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!