Declaring Methods  «Prev 

Advanced Overloading: Overloading with ambiguous types

The following example contains code that shows how 4 different methods will respond when called with different dataypes.

class AdvancedOverloading {
 void probe(int... x) {
  System.out.println("In int: x= " + x);

 void probe(Integer x) {
  System.out.println("In Integer: x= " + x);

 void probe(long x) {
  System.out.println("In long: x= " + x);

 void probe(Long x) {
  System.out.println("In Long: x= " + x);

 public static void main(String[] args) {
  Integer a = 2;
  new AdvancedOverloading().probe(a); 
  int b = 3;
  new AdvancedOverloading().probe(b);  
  long l = 5;
  new AdvancedOverloading().probe(l);  
  Long m = new Long(7);
  new AdvancedOverloading().probe(m);  
/* Program output 
In Integer: x= 2
In long: x= 3
In long: x= 5
In Long: x= 7

Question: What will be the result of an attempt to compile and run the following code?
class Test { 
 static Object test="hello";
 void f(Object x){
 void f(String x){
 void f(StringBuffer x){
 public static void main(String[] args) {
  Test t=new Test(); 

Please select 1 option:
  1. Prints "String"
  2. Prints "StringBuffer"
  3. Prints "Object"
  4. Compiler complains about an ambiguous method call.
  5. Exception thrown at runtime.
  6. None of the above.

Answer: C
Choice C is the correct answer. Here the method f is overloaded with
1) Object, 2) String and 3) StringBuffer arguments. The String literal "hello" is assigned to the variable test which is of Object type. Here even though the actual object passed is String type, the object reference is of Object type. The Object type can be assigned only to an Object type reference variable, so the only method which matches in this case is the one which takes Object as the argument. So there is no ambiguity here, the output is "Object". The correct answer is: Prints "Object"