Search code examples
javaupcasting

automatic upcast when you call function with null


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

Solution

  • 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.