0

Why is this code printing String... null?

class OverloadingTest {
            
    public void display(String ref){
        System.out.println("String..."+ref);
    }
            
    public void display(Object ref){
        System.out.println("Object..."+ref);
    }
            
    public static void main(String[] args) {
        OverloadingTest test=new OverloadingTest();
        test.display(null);
                 
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Nitesh Nehra
  • 29
  • 1
  • 7
  • 1
    That's how overloading works, it will take nearest specific data type when there's a conflict with Object and specific data type. – Pradeep Simha Apr 14 '22 at 06:38
  • By the way, this has nothing to do with [polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) – Federico klez Culloca Apr 14 '22 at 06:47
  • @FedericoklezCulloca Or [maybe](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Ad_hoc_polymorphism) it does? – Olivier Apr 14 '22 at 06:58
  • 1
    @Olivier uh, first time I see it used in that context. You learn something new every day. (including learning to read the whole article when you link to it :P) – Federico klez Culloca Apr 14 '22 at 07:07

1 Answers1

-3
  1. Where's the polymorphism? The title says there is, but there's none in the code.

  2. If you used a proper IDE or enabled warnings, you would get a warning, or depending on your warning settings, even a compile error, for the line test.display(null);, telling you that that call is ambiguous.
    And then you'd have to cast it to test.display((String) null); or test.display((Object) null);

Update

Recent versions of Eclipse (using Eclipse Build) will NOT show the "ambiguous method call" warning anymore. The option to highlight those is missing in the Java Compiler section.

JayC667
  • 2,418
  • 2
  • 17
  • 31