Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting confused by getting FileNotFoundException [duplicate]

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?

like image 231
Evgeniy Viktorov Avatar asked Dec 05 '25 03:12

Evgeniy Viktorov


1 Answers

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.

like image 179
SomeJavaGuy Avatar answered Dec 08 '25 00:12

SomeJavaGuy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!