aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloading methods (null argument) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overloading methods (null argument)" Watch "Overloading methods (null argument)" New topic
Author

Overloading methods (null argument)

Gosia Wittemann
Ranch Hand

Joined: Nov 02, 2007
Posts: 50
It's a question from JavaBelt exam:

What is the output of the following code?

01: public class A {
02: public static void test(Object a) {
03: System.out.println("Object");
04: }
05: public static void test(String a) {
06: System.out.println("String");
07: }
08:
09: public static void main(String args[]) {
10: test(null);
11: }
12: }

The answers:
Object
String
Compilation error
Runtime error

I though it should be an object, the right answer is a String, but I don't understand why.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39547
    
  27
It's a case of the most specific applicable method being called, and String is more specific than Object.

An interesting experiment would be to add another method that takes some other class (e.g. a StringBuffer), and to answer the question for that class.


Ping & DNS - updated with new look and Ping home screen widget
Sergey Petunin
Ranch Hand

Joined: Dec 16, 2007
Posts: 44
The method with the most concrete subclass is selected. String is a subclass of Object, and null can be cast to any class, so the String method is selected.
Serg Masow
Ranch Hand

Joined: Dec 17, 2007
Posts: 49
the compiler always choose the most specific method, which will be invoked. This blog linkdecribes very well the choose of the "most specific method"


SCJP 6.0 [95%] OCP EJBD 6.0 [93%]
Gosia Wittemann
Ranch Hand

Joined: Nov 02, 2007
Posts: 50
Thanks for your answers. Of course, I should have thought of it.

I tried it with a method with a StringBuffer type parameter and you get a:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method test(Object) is ambiguous for the type A

as expected.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overloading methods (null argument)
 
Similar Threads
over loading
Method with null as arg
about null
Strings
explain the out put