The order of method calls in Java


The output to the console in this case is FileNotFoundException. How exactly is the selection of the desired method to call performed?

public class Overload {

    public void method(Object o) {
        System.out.println("Object");
    }

    public void method(java.io.FileNotFoundException f) {
        System.out.println("FileNotFoundException");
    }

    public void method(java.io.IOException i) {
        System.out.println("IOException");
    }

    public static void main(String[] args) {
        Overload test = new Overload();
        test.method(null);
    }
}
Author: m. vokhm, 2018-10-15

2 answers

The compiler selects the method that has the most specific type of the parameter causing the ambiguity (further from the root of the hierarchy). In your example, FileNotFoundException is a descendant of IOException, and IOException is a descendant of Object (indirect, through Exception and Throwable), i.e. the extreme in the inheritance tree -- FileNotFoundException -- it will be selected. If the classes are in different branches of the inheritance hierarchy, there will be a compilation error. In your example, try replacing IOException with EOFException (also a direct descendant of IOException), or FileNotFoundException with String, for example -- the compiler won't understand you.

 4
Author: m. vokhm, 2018-10-15 19:52:24

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

JLS 15.12.2.5

 2
Author: Sergey Gornostaev, 2018-10-15 19:42:07