使用java中的upcasting调用“覆盖”私有方法 [英] “overriding” private methods with upcasting call in java

查看:153
本文介绍了使用java中的upcasting调用“覆盖”私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
    }
}

如上面的代码所示,当DerivedWithOutD没有覆盖方法d(),它调用f()属于PrivateOverride,那是因为PrivateOverride的方法f()不能被覆盖吗?但是从PrivateOverride继承的d()应该属于DerivedWithOutD,为什么d()调用私人f()?为什么DerivedWithD类似乎做覆盖,并且可以调用public f()?另外,当我将PrivateOverride的f()更改为public时,它全部打印Derived 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 !

推荐答案

子类不能覆盖私有方法。如果子类声明一个方法与父类中的私有方法具有相同的签名,则子类方法不会覆盖超类方法。

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.

当您调用方法 d()时,如果 d()未被子类覆盖,则执行方法是 PrivateOverride d()。当该方法调用 f()时,它会看到中定义的私有 f()方法PrivateOverride 。由于该方法未被覆盖(因为它不能),它调用该方法而不是子类的 f()方法。

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.

如果 d()被覆盖,则 d()方法执行子类 DerivedWithD 。当该方法调用 f()时,它调用 DerivedWithD <的 f()方法/ code>。

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.

如果 f()不再是私人的, f()子类中的方法现在会覆盖超类的 f()方法,因此

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.

这篇关于使用java中的upcasting调用“覆盖”私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆