3

I've got that piece of code and just getting FileNotFoundException.

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);   
    } 
} 

Any thoughts why does it happen?

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31

2 Answers2

5

Because it does access the most specific method, which in this case is method(java.io.FileNotFoundException f)

inheritence order from FileNotFoundException

java.lang.Object -> java.lang.Throwable -> java.lang.Exception -> java.io.IOException -> java.io.FileNotFoundException.

As you can see, the IOException inherits from Object (at some point) which makes it more specific then Object. And the FileNotFoundException is more specific then IOException. In the end the compiler decides that it should call the method with the FileNotFoundException as parameter.

If there are two methods that are equally specific your code wouldn´t compile with the error that there is an ambiguous method call.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
0

Most specific method argument is chosen for overloaded methods

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5

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.

shakhawat
  • 2,639
  • 1
  • 20
  • 36