Method overload and null value transfer

I have the following 2 methods overloaded in class:

public class Test{ public static void main(String []args) throws ParseException{ Test t = new Test(); t.testMethod(null); } public void testMethod(Object o){ System.out.println("Object"); } public void testMethod(String s){ System.out.println("String"); } } 

When I call testMethod , it prints "String".

When I add another overloaded method:

 public void testMethod(StringBuilder sb){ System.out.println("String"); } 

This causes a compiler error: The method testMethod is ambigous for type Test ..

All this happens when I call a method using null

My questions:

  • Why is it printing a line, not an object?
  • Why is there a compilation error when adding the third method?
+5
source share
3 answers

Why is it printing a line, not an object?

The java compiler selects a method with the most specific or least common argument. Since Object is the superclass of all classes (including String ), the String class is selected.

Why does a compilation error occur when adding a third method?

Since String and StringBuilder lower than Object , the compiler will find the call ambiguous, since both String and StringBuilder can accept null , the compiler cannot determine which method to call, therefore, you get an error at compile time.

If you try to do the same with IOException and FileNotFoundException instead of String and StringBuilder , you will find that FileNotFoundException because it is less general.

+1
source

Method resolution works by choosing the most specific method applicable to the given arguments. In your first case, String more "specific" than Object (since it is a subclass of Object ), and so the String method is chosen.

When you add another method that accepts a StringBuilder , both the String method are equally "specific" (they are both direct subclasses of Object ), so there is ambiguity about what should be selected, hence the error.

+3
source

In case1, String inherits from Object, they are in the inheritance chain, zero coincides with them, the compiler chooses a more specific type - String.

In case 2 String and StringBuilder are not in the inheritance chain, the compiler cannot select a more specific type.

Details of method overloaded resolution are described in JLS 15.12.2.

0
source

Source: https://habr.com/ru/post/1208151/


All Articles