aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes how to invoke the overload method when use null as argument? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "how to invoke the overload method when use null as argument?" Watch "how to invoke the overload method when use null as argument?" New topic
Author

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

fei peng
Ranch Hand

Joined: Sep 15, 2003
Posts: 40
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

Joined: Nov 04, 2003
Posts: 46
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!


Harikumar G<br />SCJP 1.4
Uma Balu
Ranch Hand

Joined: Aug 22, 2003
Posts: 61
Hi,
The question is answered here
Regards,
Uma..
Rahul JG
Ranch Hand

Joined: Jun 05, 2002
Posts: 44
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.


Rahul
fei peng
Ranch Hand

Joined: Sep 15, 2003
Posts: 40
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

Joined: Nov 19, 2003
Posts: 49

Have a look at JLS 15.12.2.2
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to invoke the overload method when use null as argument?