Ankit
Ankit

Reputation: 639

Choosing the Most Specific Method - Tricky Method Overloading?

I have gone through this link; but I am getting confused with the following sample code:-

public class NullTest {

   public static void method(Object obj){
     System.out.println("method with param type - Object");
   }

   public static void method(String str){
     System.out.println("method with param type - String");
   }

   public static void method(StringBuffer strBuf){
     System.out.println("method with param type - StringBuffer");
   }

   public static void main(String [] args){
     method(null); //... compile-time error!
   }
}

Error that I am getting is :-

ankit@stream:/home/Data/JAVA/practice$ javac trickyMethodOverloading.java 
trickyMethodOverloading.java:16: error: reference to method is ambiguous, both method method(String) in trickyMethodOverloading and method method(StringBuffer) in trickyMethodOverloading match
     method(null); //... compile-time error!

Any suggestions, please

Upvotes: 0

Views: 885

Answers (2)

imnd_neel
imnd_neel

Reputation: 109

In such a case of method overloading, the most specific method, or in other words, method belonging to deepest Class in the hierarchy of Inheritance tree is chosen at runtime, as long as the classes used belong to the same branch in inheritance tree, so that one class can be found without ambiguity. (from my own understanding, not from java documentation :))

However, in your example, you have 2 overloaded methods with String and StringBuffer respectively, which do not belong to same branch in inheritance tree. This is why compiler is complaining.Different branches in Inheritance Same branch in inheritance tree

This kind of example works if you have a hierarchy of say, 3 classes A, B, C where B extends A and C extends B. In this case if you have

public class NullTest{

   public static void method(A a){
     System.out.println("method with param type - A");
   }

   public static void method(B b){
     System.out.println("method with param type - B");
   }

   public static void method(C c){
     System.out.println("method with param type - C");
   }


   public static void main(String [] args){
     method(null);// compiles successfully and will print- "method with param type - C"
   }
}

This works because A, B and C belong to same hierarchy in inheritance tree. Therefore compiler simply tries to go to the deepest level and it can find a single class without ambiguity(C in this case). Also, if you remove either String or StringBuffer from your code, it'll work.

Upvotes: 1

GraphicsMuncher
GraphicsMuncher

Reputation: 4641

You have the same name for all of your methods. The only way Java can now distinguish them is by the argument they receive so it knows which one to use. However, using null does not narrow anything down, so your compiler can't finish compiling because it doesn't know which one to use.

Upvotes: 2

Related Questions