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
266 views
in Technique[技术] by (71.8m points)

Override "private" method in java

There something ambiguous about this idea and I need some clarifications.

My problem is when using this code:

public class B {

    private void don() {
        System.out.println("hoho private");
    }
    public static void main(String[] args) {
        B t = new A();
        t.don();
    }
}

class A extends B {
    public void don() {
        System.out.println("hoho public");
    }
}

The output is hoho private.

Is this because the main function is in the same class as the method don, or because of overriding?

I have read this idea in a book, and when I put the main function in another class I get a compiler error.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the @Override annotation when you intend to override,

class A extends B {
    @Override
    public void don() { // <-- will not compile if don is private in B.
        System.out.println("hoho public");
    }
}

In this case why didn't compiler provide an error for using t.don() which is private?

The Java Tutorials: Predefined Annotation Types says (in part)

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.


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

...