• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Method Overloading

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Question :Read the code below.What Will be the result of attempting to compile and run the code below.
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[]) {
new AQuestion().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.

Given Answer is 3 , I don�t understand this, how can this compile . In the same Class if I add another overloaded method taking any type of Object like StringBuffer, Wrappers etc .
public void method(StringBuffer s)
{ System.out.println("AQuestion Version"); }

then the compiler gives error
Reference to method is ambiguous. It is defined in void method(java.lang.String) and void method(java.lang.StringBuffer) question.method(null);

Regards Sameet
 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sameet, I changed the program to include just one method as follows:
public class AQuestion {
public void method() {
System.out.println("No Parameter Version");
}
public static void main(String args[]) {
new AQuestion().method(null);
}
}

It gave me the following compilation error.
Wrong number of arguments in method.
new AQuestion().method(null);

The Java documentation says :-
The Kinds of Types and Values
Type:
PrimitiveType
ReferenceType
There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type.
The null reference can always be cast to any reference type. In practice, the Java programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.
Since the null literal can be of any reference type, I changed the program again and added the method with the Object reference as a parameter.
public class AQuestion {
public void method(Object o) {
System.out.println("Object Verion");
}
public void method() {
System.out.println("No Parameter Version");
}
public static void main(String args[]) {
new AQuestion().method(null);
}
}

The program now calls the method with the Object reference. Which means that it is being implicitly cast to the "Object" reference type. This means that if we define any more methods with any Reference Type parameters, it should give us an error. This is what stumped me. It allows another method with a Reference Type parameter like String and calls that method on being executed. And as you said it gives a "Reference to ambiguous method" compilation error if a third method with an Object Reference type is included.
Why does it not give an error if methods with two object type references (Object and String) are defined? And why does it object to two other object type references (String and StingBuffer)?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi jayashree murugan
I Think you got my point right. the Program allows two ovreloaded Methods One Accepting Arg of Type Object & other also some other arbitary Object. This Compiles & runs Fine . but u add 3rd overloaded method then the compilar wakes up to give a compile time error
Even if you remove the overloaded Method having Object as Argument then you get a compile time error for the other two methods
regards Sameet
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sameet,
Your example is a case of overloaded methods, not overrided methods.
When you pass null to overloaded methods, the java compiler tries to select the one that is lowest in the class hierarchy. Both String and StringBuffer are subclasses of Object, it has to choose one class between them. As none of them is a subclass of the other (apart from being a subclass of Object), the java compiler does not know how to choose, because each one is a good candidate as an argument to the overloaded method. It therefore gives you an error.
The following program illustrates my point. It prints out "Lower version".
<pre>
public class AnQuestion
{
private class AnSuper {}
private class AnMiddle extends AnSuper {}
private class AnLower extends AnMiddle{}
public void method(AnSuper o)
{
System.out.println("Super Verion");
}
public void method(AnMiddle o)
{
System.out.println("Middle Version");
}
public void method(AnLower o)
{
System.out.println("Lower Version");
}
public static void main(String args[])
{
AnQuestion question = new AnQuestion();
question.method(null);
}
}
</pre>
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I can add an additional observation, but still no explanation. The following class compiles without error:

I tried this out with the hope that the superclass relationship of Object to String (in Sameet's original comment) is the reason that the code compiles without error. The example above was intended to extend that reasoning to a three level class hierarchy.
When executed the code will display "Integer Version" -- the most specific of the three classes.
So the rhyme seems to be "when the argument is null invoke the most specific method if it can be unambiguosly determined", but I haven't figured out the reason.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried the same program with a difference,
import java.util.Vector;
class test
{
public void method(Object o)
{
System.out.println("Object Verion");
}
public void method(Vector s)
{
System.out.println("Vector Version");
}

*public void method(String s)
{
System.out.println("String Version");
}*/
static public void main(String[]o)
{
new test().method(null);
}
}
I think the catch of the problem would in the Object version. (you comment it and it does not work in the 2 method version itself).
While all subclasses like Vector or Stack or StringBuffer are in turn Object's they take the subclass Version, but when you combine (i.e commenting the Object version type) only overloaded methods that are sub classes of Object , you get a compiler error!!!
This maybe a clue but I still dont understand why this happens.
Anyway its a good question
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Edward
thank u for this valuable peice of code.
regards Sameet
 
jayashree murugan
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In case there are overloaded methods whose parameters are classes in one hierarchy, it calls the one which is lowest in the hierarchy. However, you cannot include methods with a reference to a peer object type. Then the compiler is unable to decide which method to call. Which is why the program with Object and String worked, but the one with String and StringBuffer(peer objects) did not.
The overloaded method arguments must be object references of one single hierarchy
The following program will work even without the object version method since Container and Component are in the same hierarchy.
import java.awt.*;
import java.applet.*;
public class xyz{
/*public void display(Object o){
System.out.println("Object version");
}*/
public void display(Component o){
System.out.println("Component version");
}
public void display(Container o){
System.out.println("Container version");
}
public void display(){
System.out.println("No parameters");
}
public static void main(String str[]){
new xyz().display(new Applet());
new xyz().display(null);
}
}
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jayshree. thats a very good observation and good information too. I guess I learnt something today.
Thnks again.
 
We must storm this mad man's lab and destroy his villanous bomb! Are you with me tiny ad?
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic