Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Compilation Error...

 
Ivaturi Srinivas
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why the following program gives Compilation Error?
public class AQuestion
{
public void method(StringBuffer sb)
{
System.out.println("StringBuffer Verion");
}
public void method(String s)
{
System.out.println("String Version");
}
public static void main(String args[])
{
AQuestion question = new AQuestion();
question.method(null);
}
}
If I replace null with some string "AKP" String version is called.
Please tell me the reason.
Thanks
Srinivas Ivaturi
 
Pratibha Malhotra
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Java compiler has given sufficiant information..

AQuestion.java:10: reference to method is ambiguous, both method method(java.lang.StringBuffer) in AQuestion and method method(java.lang.String) in AQuestion match question.method(null);

Ur code has method() in overloaded form.........

public void method(StringBuffer sb) { print("StringBuffer Verion"); }
public void method(String s) { print("String Version"); }

Depending on the parameter wich u will pass while invoking any one of these methods will decide which method has to actually execute....
Now the matter of fact is both StringBuffer and String variable/argument can take null as their value. And therefore Compiler can not decide which overloaded method has to be executed.
I hope this will help :-)
 
Sahul Yasin
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From one of Dan's Mock Exam Answer list :

The type of the argument is null and could be converted to any of the types StringBuffer or String by method invocation conversion. Both are applicable, but none of the two is more specific than other. The ambiguity results in a compile-time type error.

If there is no inheritence relationship between this argument objects when we pass the null ,the compiler can not able to find the more specific object , leads to compile time exception .
[ January 13, 2004: Message edited by: Mohamed Yasin ]
 
Ashok Paulraj
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with your explanations, but does the same happen if you pass an int to a method that has got 2 overloaded forms (float & double). Clarify me !!
~ Shalini
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic