问题描述
我遇到了这种情况。我们有一个类让我们说主要有私人方法打印。另一个类Main1扩展了Main类并重新定义了print方法。由于main1是Main1类的对象,我希望调用main1 print方法...
I came across this scenario. We have a class lets say Main having a private method print. There is another class Main1 which extends Main class and redefines the print method. Since main1 is an object of Main1 class, I expect main1 print method to get called...
public class Main {
public static void main(String[] args) {
Main main1 = new Main1();
List<String> list = new ArrayList<String>();
main1.print(list);
}
private void print(List<String> string) {
System.out.println("main");
}
}
class Main1 extends Main {
public void print(List<String> string) {
System.out.println("main1");
}
}
在这种情况下,当我们运行程序时,它打印主要。它真的让我感到困惑,因为该方法是私有的,甚至不是Main1类的一部分。
In this case, when we run the program, it print "main". It really confuses me as that method is private and is not even part of Main1 class.
推荐答案
答案并不太难:
-
main1
变量的类型是Main
(不Main1
) - 所以你只能调用该类型的方法
- 唯一可能的方法是
print
,它接受List< String>
主
是私人 - 调用代码在类
中主
所以它可以调用该类中的私有方法
- the type of the
main1
variable isMain
(notMain1
) - so you can only call methods of that type
- the only possible method called
print
that accepts aList<String>
onMain
is the private one - the calling code is inside the class
Main
so it can call a private method in that class
因此 Main。将调用print(List< String>)
。
请注意,更改 main1的类型
到 Main1
将导致其他 打印(List< String>)
被调用的方法。
Note that changing the type of main1
to Main1
will result in the other print(List<String>)
method being called.
这篇关于Java私有方法覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!