覆盖“私人” java中的方法 [英] Override "private" method in java

查看:77
本文介绍了覆盖“私人” 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");
    }
}

输出 hoho private

这是因为main函数与方法 don ,还是因为压倒一切?

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

我在一本书中读过这个想法,当我把 main 函数在另一个类中我得到编译器错误。

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

推荐答案

你不能覆盖 private 方法。如果您将 A 转换为 B ,则不可见。您可以覆盖受保护的方法,但这不是您在此处所做的(是的,如果您移动<$ c,此处为$ c> main A 然后你会得到另一种方法。我会推荐 @Override 注释,

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




在这种情况下,为什么编译器没有提供使用<$ c $的错误c> t.don()这是私人

Java教程:预定义注释类型说(部分)


虽然在重写方法时不需要使用此注释,但是lps以防止错误。如果标有 @Override 的方法无法正确覆盖其某个超类中的方法,则编译器会生成错误。

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.

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

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