gpt4 book ai didi

java - 在java中覆盖 "private"方法

转载 作者:太空狗 更新时间:2023-10-29 23:01:46 24 4
gpt4 key购买 nike

这个想法有些模棱两可,我需要一些澄清。

我的问题是在使用这段代码时:

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 方法在同一个类中,还是因为覆盖?

我在一本书中读到过这个想法,当我将 main 函数放在另一个类中时,出现编译错误。

最佳答案

您不能覆盖私有(private) 方法。如果将 A 转换为 B,它是不可见的。您可以覆盖protected 方法,但这不是您在这里所做的(是的,如果您将main 移动到A 然后你会得到另一种方法。当你打算覆盖时,我会推荐 @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说(部分)

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 - 在java中覆盖 "private"方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com