An important concept of method Overloading

Let’s discuss method overloading in java example and see what will be the outcome.

Suppose if there are two methods having the same name but different types of parameters. The parameters are non-primitive types and we are calling the method by a null value. So both methods can accept the null value. But which one gets called?

public class MainClass 
{
    public static void main(String[] arg) 
    {
    	MainClass obj = new MainClass();
    	obj.show(null);
    }
    
    public void show(Object obj)
    {
    	System.out.println("Method with object parameter");
    }
    
    public void show(String obj)
    {
    	System.out.println("Method with String parameter");
    }
}

Output: Method with String parameter

Reason: Java will always try to use the most specific applicable version of a method that’s available. Here Object class is the superclass of String class and String is more specific here.

Why ? we can’t overload by changing the return type of method


If we are creating two methods with the same name but different return types. Then the program will be a show compilation error. Let’s see method overloading in java example with a different scenario.

Example:

class ExampleOfMethodOverloading 
{
	public void show(String name)
	{
		System.out.println("Name of person = "+name);
	}
	
	public boolean show(String name)
	{
		System.out.println("Person name is = "+ name);
	}
	public static void main (String [] args) 
	{
		ExampleOfMethodOverloading example = new ExampleOfMethodOverloading();
		// If user providing parameter of String type then first method called
		example.show("Ram");
		// If user providing parameter of int type then second method called
		example.show("Sham");
	}
}

Here, the compiler can’t determine which show() method should be called?

6 thoughts on “An important concept of method Overloading”

  1. you said parameters are primitive types.
    i don’t agree because String is a non-primitive data type, because it refers to an object. The String object has methods that are used to perform certain operations on strings.

    Reply
  2. string is nullable.
    object is a parent class for all existing classes in the Java.

    here polymorphism comes into picture.. that
    parent class reference is equal to child class.

    if compiler is smart it will never cast the object into string first and then assign null.

    it will definitely go for the method who has a string type para.

    Reply
    • Java will always try to use the most specific applicable version of a method that’s available. Here Object class is the superclass of String class and String is more specific here.

      Reply

Leave a Comment