CrazyEngineers
  • 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
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • sookie

    MemberMay 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]
    Are you sure? This action cannot be undone.
    Cancel
  • Anoop Kumar

    MemberMay 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()));

    }
    }
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register