3

This code prints out MyUrgentException. Could anybody explain why?

class MyException extends Exception{
}

class MyCriticalException extends MyException{
}

class MyUrgentException extends MyCriticalException{
}

public class Test{
  public void handler(MyException ex){
    System.out.println("MyException");
  }

  public void handler(MyCriticalException ex){
    System.out.println("MyCriticalException");
  }

  public void handler(MyUrgentException ex){
    System.out.println("MyUrgentException");
  }

  public static void main(String [] args){
    new Test().handler(null);
  }
}
Fedor Skrynnikov
  • 5,521
  • 4
  • 28
  • 32

1 Answers1

3

See the answer for a similar question.

See JLS 15.12.2:

[...] There may be more than one such method declaration, in which case the most specific one is chosen.

So to answer your question. When several overloaded methods are applicable for a specific type, the most specific, or "upcast" if you want, methods is called.


From a intuitive perspective this also makes sense. When you declare:

public void handler(MyException ex) {...}

You are saying: "I know how to handle a general MyException".

And when you are declaring:

public void handler(MyUrgentException ex){...}

You are saying: "I know how to handle the specific case of a MyUrgentException", and therefore also the general case of a MyException.

Community
  • 1
  • 1
Bjarke Freund-Hansen
  • 28,728
  • 25
  • 92
  • 135