Overloading Behaviour in Java

ankur8819

ankur8819

@ankur8819-Y8pKwX Oct 25, 2024
public class testOverload {
public void xyz(Object o){
System.out.println("o");
}
public void xyz(Exception o){
System.out.println("exc");
}
public void xyz(RuntimeException o){

System.out.println("runtime");

}
public static void main(String[] args) {
testOverload t= new testOverload();
t.xyz(null);
}
}
The above method gives runtime as Output.Can anyone explain this behaviour of JRE.
null is a type of Object so it should give "o" as output.
More specifically if you include one more overloaded version of xyz method as
public void xyz(NullPointerException o){

System.out.println("null");

}
then it would print null which suggests that its treating null as an object of NullPointerException Class.
Any comments on this?

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • sookie

    sookie

    @sookie-T06sFW May 27, 2012

    It is because of exception hierarchy. At runtime, "null" is not passed as an object it is passed as a "null" value means no value hence it goes in exception flow and looks for nearest parent object.
    [​IMG]
  • Anoop Kumar

    Anoop Kumar

    @anoop-kumar-GDGRCn May 27, 2012

    Some corrections here...
    1.null is not a object type as if null would be object it should support java.lang.Object method like equals().

    2.Overloading returns most specific behaviour that is why when it caught an exception it returns
    RuntimeException exception object instead of Exception object.
    try this:


    public class testOverload {
    public void xyz(Object o) {
    System.out.println("o");
    }
    public void xyz(Integer o) {
    System.out.println("Integer");
    }
    public void xyz(String o) {
    System.out.println("String");
    }
    public void xyz(Exception o) {
    System.out.println("exc");
    }
    public void xyz(RuntimeException o) {
    System.out.println("runtime");
    }
    public static void main(String[] args) {
    testOverload t = new testOverload();
    t.xyz("dfa");
    t.xyz(123);
    t.xyz((new Object()));

    }
    }