Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading methods (null argument)

 
Gosia Wittemann
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sergey Petunin
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the compiler always choose the most specific method, which will be invoked. This blog linkdecribes very well the choose of the "most specific method"
 
Gosia Wittemann
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic