For the following segment of java code, the method of “run” occurs four times. I am quite confusing about the relationships of these four occurrences of “run”. The original code is pretty long, I just keep the part that is related to my question.
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. }
Can I understnd the invoking sequence of this segment of code as follows.
At first, he run method at line 5 is called. Due to its particular parameter setting, 3 parameters, the compiler automatically uses the run method defined in line 13. ( if we only have one parameter in line 5, then compiler will use the run method defined in line 9 instead.
For the run method defined in line 9, it will call run method at line 10, which essentially is the run method defined at line 13.
Is my understanding correct?
Your basic analysis is correct.
(just to clarify the point that others have made: overloading is when methods have the same name but different signatures, whereas overriding is when a method has the same name and argument types as a method in a superclass)
For future reference, you should be aware that method resolution (name + arguments -> method selection) in Java, in the case of overloaded methods, can actually be quite difficult to understand. The exact behavior used is written up in the Java Language Spec (JLS), section 15.12, and involves a few general subtleties:
Overloaded method resolution is done at compile time, not at runtime. (selection among method overrides with the same signature is done at runtime, based on the most specific subclass’s method.) If the compiler knows an argument is an instance of
Foo(e.g. its class isFooor a subclass ofFoo) then it will useFooas the argument’s class, not its “real” class.Issues that determine which method is used include:
...as the last argument e.g.foo(Object a, String... b))floatvsFloatThis is complex but you have the basic understanding.