Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

polymorphism - “overriding” private methods with upcasting call in 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();
    }
}

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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...