Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to invoke the overload method when use null as argument?

 
fei peng
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,everyone
in this program:
public class Test {

public void method(Object o) {
System.out.println("Object Version");
}
public void method(String s) {
System.out.println("String Version");
}
public static void main(String[] args) {
Test test = new Test();
Object o=new Object();
test.method(null);
}
}
I think the method use Object as argument should be invoked,but actually
the method use String as argument be invoked,how this happen?
 
H Gokulam
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice One!
This kind of overloading is possible only with classes of same path in the heirarchy. If you try to add another method with parameter as 'Test', it doesn't compile.
Whenever null is passed as parameter to this kind of methods the method with parameter lowest in the heirarchy is taken. I don't have any explanation for this. This is my observation.
If anybody knows the actual reason behind this please provide!
 
Uma Balu
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The question is answered here
Regards,
Uma..
 
Rahul JG
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this case both methods are applicable and accessible, so the compiler selects the one that is most specific.
Since String inherits from Object the method with the String argument is more specific.
 
fei peng
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot.
I understand that since the compile must find the right overload method in compile time,so there have to be a rule to decide which one is called,form bottom to up in class hierachical,that's all.
 
Dimple Kaushik
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Have a look at JLS 15.12.2.2
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic