3

It would be great if anyone can explain below. Why print(String s) method is called in below example and print(Object o) not called.

package com.example;

public class DemoTest {

    public void print(Object o){
        System.out.println("Object");
    }
    public void print(String s){
        System.out.println("String");
    }
    public static void main(String[] args) {
        DemoTest dt = new DemoTest();
        dt.print(null);

    }
}
Charles Caldwell
  • 16,649
  • 4
  • 40
  • 47
Juns
  • 511
  • 1
  • 5
  • 10

1 Answers1

1

Taken from Strange Java null behavior in Method Overloading

"That is because String class extends from Object and hence is more specific to Object. So, compiler decides to invoke that method. Remember, Compiler always chooses the most specific method to invoke."

Community
  • 1
  • 1
Mark
  • 418
  • 1
  • 4
  • 13