Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatic upcast when you call function with null

Tags:

java

upcasting

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);
  }
}
like image 525
Fedor Skrynnikov Avatar asked Apr 14 '26 21:04

Fedor Skrynnikov


1 Answers

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.

like image 134
Bjarke Freund-Hansen Avatar answered Apr 17 '26 11:04

Bjarke Freund-Hansen



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!