This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Correct version of a method. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Correct version of a method." Watch "Correct version of a method." New topic
Author

Correct version of a method.

Tejaswini Shirkhedkar
Greenhorn

Joined: Jun 22, 2004
Posts: 17
public class AQuestion
{
public void method(Object o)
{
System.out.println("Object Verion");
}
public void method(String s)
{
System.out.println("String Version");
}
public static void main(String args[])
{
AQuestion question = new AQuestion();
question.method(null);
}
}
Answers
1 The code does not compile.
2 The code compiles cleanly and shows "Object Version".
3 The code compiles cleanly and shows "String Version"
4 The code throws an Exception at Runtime.

The answer given is 3.
The default value for object reference is also null as it is for an uninitialized string reference.Why does, then, the compiler does not complain about ambiguous method call?
Thanks!

Teju
arnel nicolas
Ranch Hand

Joined: Dec 16, 2003
Posts: 149
From my understanding, both methods are applicable not actually ambigous as you have mentioned. The compiler will look for the most specific method that can accomodate the value passed in the parameter method.

Example on an ambigous call:


public class Ambigous{


void setNumber(long n) {
System.out.println(n);
}

void setNumber(int n) {
System.out.println(n);
}

public static void main(String args[]) {
new Ambigous().setNumber(2);
}
}

--Hope this help
arnel nicolas
Ranch Hand

Joined: Dec 16, 2003
Posts: 149
Sorry , i need to make a few correction with my example for ambiguous class above. Those codes will work fine. See my example below:

public class Ambiguous{

class AnotherObject{}

void aMethod(Object s) {
System.out.println("Object");
}

void aMethod(String s) {
System.out.println("String");
}


void aMethod(AnotherObject s) {
System.out.println("AnotherObject");
}

public static void main(String args[]) {
new Ambiguous.aMethod(null);
}
}

Hope this will help you.
Jong Limb
Greenhorn

Joined: May 08, 2004
Posts: 12
String is derived from Object and is therefore, more specific.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Correct version of a method.
 
Similar Threads
Mock test Q
Doubt in overloaded method related question
Constructor Overloading
question in javaquiz
String and Object class