• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A good one on overloading... .

 
Rafa Barcel� Bauz�
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.
I have a little doubt on overloading methods...

Why is m(ArrayList a) executed?, Is because it's more inheritance especific the parameter to m method or something like that???

public class Pruebas {

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

public void m(Object o) {
System.out.println("o");
}

public void m(ArrayList a) {
System.out.println("s");
}

}

***************************************************

After this, I put another method like this:

public void m(LinkedList l) {
System.out.println("l");
}

and the compiler says:

The m(Object) is ambiguous.

I supose it's because LinkedList ant ArrayList are in the same
inheritance level.

Can someone explain me how overloading works in a situation like this??

Thanks!!!
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


The overloaded method which has smallest argument having width that is enough for the calling parameter (if the argument type is primitive) or the refernce type down in the inheritance tree which fits the calling parameter,is a right candidate for this overloaded method invocation.Hence the method m(ArrayList a) will be called.


LinkedList and ArrayList are the implementation of same interface so they are sibling (which can not be checked by the compiler,I guess),not sub-class /super-class.So when the compiler sees such type of code it feels the amiguity for not having the answer for the question "which one to invoke,both are eligible?",so stops compilation.

Correct me if Im wrong.
 
wise owen
Ranch Hand
Posts: 2023
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rafa Barcel� Bauz� posted November 02, 2006 04:33 AM

Why is m(ArrayList a) executed?, Is because it's more inheritance especific the parameter to m method or something like that???



Exactly. This behaviour is also true for primitive values.

What I found a little tricky is that the specificity only looks for the reference type, not for the object type. So with a polyporph variable you can run into a trap:


Point is more specific than an object, but only the reference type counts here.
so the Object mixed will go into the Object method. And "Object" is printed out.



Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic