aspose file tools*
The moose likes Java in General and the fly likes Overloading behaviour In Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Overloading behaviour In Java" Watch "Overloading behaviour In Java" New topic
Author

Overloading behaviour In Java

Ankur Luthra
Ranch Hand

Joined: Dec 13, 2010
Posts: 36
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?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

When posting code, please UseCodeTags(⇐click) so it will be readable.

The reason for the behavior you're seeing is that the compiler (not the JRE) picks the "most specific" signature that can match the args. The null arg can match Object or Exception or RuntimeException. Since RuntimeException is the most specific, that is the signature that the compiler chooses.

Details can be found here.
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3611
    
  60

Ankur Luthra wrote:... null is a type of Object ...

Just to clarify: null is a literal and is of the null type (see here).

If it was of the Object type, you could not assign it to variable of any other type (eg. a String).
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19760
    
  20

Jeff is right. It works because RuntimeException extends Exception and Exception extends Object. Add another xyz method with a parameter type that is not compatible with Exception or RuntimeException (e.g. String), and your compiler will complain about ambiguity.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Rob Spoor wrote:Jeff is right. It works because RuntimeException extends Exception and Exception extends Object. Add another xyz method with a parameter type that is not compatible with Exception or RuntimeException (e.g. String), and your compiler will complain about ambiguity.


It will also complain if you have a signature whose arg is a sibling of RuntimeException, I think, since neither one would be "more specific" than the other.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19760
    
  20

Correct.
 
 
subject: Overloading behaviour In Java