开发者

automatic upcast when you call function with null

This code prints out MyUrgentException. Could anybody explain why?

class MyException extends Exception{开发者_如何学JAVA
}

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜