• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object or String?  RSS feed

 
Aafreen Moinuddin
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Guys i tried compiling the following class n it gives "string version" as the output


So my question is why does it choose to give " string version" instead of "object version" when both the methods can equally accept the null value given in the argument?

...... Any one?


public class Aclass {

public void amethod(Object o){
System.out.println("object version");

}
public void amethod(String s){
System.out.println("string version");

}

public static void main(String[] args) {

Aclass A = new Aclass();

A.amethod(null);
}
}
[ March 14, 2006: Message edited by: Aafreen Moinuddin ]
 
Joni Salonen
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The rule is: choose the most specific signature possible.

As String is a subbclass of Object, the amethod(String) method has the most specific signature, so it is chosen.

Edit: If there is no method with the most specific signature, like when you add amethod(Number n), you get a compile-time error.
[ March 14, 2006: Message edited by: Joni Salonen ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!