Search code examples
javaoopoverloadingtype-promotion

How Overloading in Java Works?


I fail to understand that why in the following code the output is "String Version". As everything is Derived from Object then why it matches to String version?

public class AQuestion
{
public void method(Object o)
{
    System.out.println("Object Verion");
}
public void method(String s)
{
    System.out.println("String Version");
}


  public static void main(String args[]) throws Exception
   {
    AQuestion question = new AQuestion();
    question.method(null);
   }
}

Output: String Version


Solution

  • Java Code

    You have to pass an object for it to take object verion

    public class TestProgram {
    
    
        public void method(Object o)
        {
            System.out.println("Object Verion");
        }
        public void method(String s)
        {
            System.out.println("String Version");
        }
    
    
          public static void main(String args[])
           {
              TestProgram question = new TestProgram();
              question.method(question);
           }
        }