Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do overloaded methods work?

public class Test1  {

    public static void main(String[] args)   {
        Test1 test1 = new Test1();
        test1.testMethod(null);
    }

    public void testMethod(String s){
        System.out.println("Inside String Method");     
    }

    public void testMethod(Object o){
        System.out.println("Inside Object Method"); 
    }
}

When I try to run the given code, I get the following output:

Inside String Method

Can anyone explain why the method with the String type parameter is getting called?

like image 853
Java_Sape Avatar asked Oct 08 '13 09:10

Java_Sape


People also ask

How does method overloading work?

Two or more methods can have the same name inside the same class if they accept different arguments. This feature is known as method overloading. Method overloading is achieved by either: changing the number of arguments.

Why would you overload a method?

Benefits of using Method Overloading Method overloading increases the readability of the program. This provides flexibility to programmers so that they can call the same method for different types of data. This makes the code look clean.


1 Answers

most specific method argument is chosen for overloaded methods

In this case, String is subclass of Object. Hence String becomes more specific than Object. Hence Inside String method is printed.

Directly from JLS-15.12.2.5

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

As BMT and LastFreeNickName have correctly suggested, (Object)null will cause overloaded method with Object type method to be called.

like image 85
Prasad Kharkar Avatar answered Oct 04 '22 08:10

Prasad Kharkar