在java中使用向上转换调用“覆盖"私有方法

2022-01-24 00:00:00 polymorphism overriding java
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() 不能被覆盖?但是 d() 继承自PrivateOverride 应该属于DerivedWithOutD,为什么d() 调用私有f()?为什么 DerivedWithD 类似乎做了覆盖,并且可以调用公共 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()没有被子类覆盖,执行的方法是PrivateOverrided().当该方法调用 f() 时,它会看到 PrivateOverride 中定义的私有 f() 方法.由于该方法未被覆盖(因为它不能被覆盖),它调用该方法而不是子类的 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()被覆盖,则执行子类DerivedWithDd()方法.当该方法调用 f() 时,它会调用 DerivedWithDf() 方法.

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() 方法超类的,因此子类的 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.

相关文章