View Feed
group-icon
Java Developers
Community of Java Developers: Get Java Programming Help from fellow Java Developers across the world.
562 Members
Join this group to post and comment.
ankur8819
ankur8819 • May 26, 2012

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?
sookie
sookie • May 28, 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 • May 28, 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()));

}
}

Share this content on your social channels -