Overloading Behaviour in Java

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

  • sookie
    sookie
    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
    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()));

    }
    }

You are reading an archived discussion.

Related Posts

Hi, I studied that a combination of an LED and a photo detector in two separate circuits could be used as an opto isolator where the light emitted by an...
Hi, I am working on a problem wherein I need to Group similar strings in an Array. i.e If my String array is say "AXPZ","BXT","PZXA","XAZP","XBT","TBX","ABCD" then I would group AXPZ,PZXA...
Internet hackers group Anonymous has finally landed in India. Here is an interesting chat of a reporter with the group. https://nh7.in/indiecision/2012/05/26/nh7-chat-anonymous/ Now the issue is, do we really need them...
Has anyone here have any experience on PCB Design Fab Assembly start up? May I know how did it go? What are the considerations? What are the challenges involved?
Google plans to warn more than half a million users of a computer infection that may knock their computers off the Internet this summer. Hackers have infected a network of...