对于下面的java代码段,“run”方法出现了四次。我对这四个“run”出现的关系感到很困惑。原来的代码很长,我只保留与我的问题相关的部分。
1. public final class Job extends AbstractJob {
2. private Job( ) {
3. }
4. public static void main(String[] args) throws Exception {
5. new Job( ).run(new Path("testdata"), output, 10 );
6. }
7.
8. @Override
9. public int run(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
10. run(input, output, alpha0);
11. return 0;
12. }
13. public void run(Path input, Path output, double alpha0)
14. throws IOException, ClassNotFoundException, InterruptedException {
15. ClusterDriver.run(directoryInput, output, alpha0);
16. }
17. }
我能否理解这段代码的调用顺序如下。
首先,他调用了第5行的run方法。由于其特殊的参数设置,3个参数,编译器自动使用第13行定义的run方法。(如果第5行只有一个参数,那么编译器将使用第9行定义的run方法。
对于第9行定义的run方法,它会调用第10行的run方法,本质上就是第13行定义的run方法。
我的理解正确吗?
最佳答案
是的,这是正确的,只不过这是方法重载,而不是重写。
该类中第 9 行和第 13 行定义了两个 run
方法,具有不同数量的参数。因此,run
方法重载。 (如果在子类中重新定义虚拟基类方法,就会发生覆盖 - 正如其注释所证明的那样,它显然发生在第 9 行定义的方法上,但这在这个特定问题中不起作用。)
并且有两次对 run
的调用(第 5 行和第 10 行),它们都解析为调用具有 3 个参数的方法(在第 13 行定义)。
关于java - 关于方法重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6387235/