-2
public class Test{

public static void m1(Object o){
    System.out.println("object called");
}

public static void m1(String s){
    System.out.println("String called");
  } 
 }

Now, here are the below cases,

  • m1("string"); output : String called
  • m1(new String("string")); output : String called
  • Object o = "string"; m1(o); output : object called
  • Object o = new String("string"); m1(o); output : object called
  • Object o = new Object(); m1(o); output : object called

Can someone please explain the above scenarios?

Abdelhak
  • 8,299
  • 4
  • 22
  • 36
BaajiRao
  • 99
  • 1
  • 10
  • 1
    every of your variables `o` are defined as an `Object`, and hence it is calling `m1(Object)`. The same happens with the call with the `String`. – SomeJavaGuy Nov 30 '15 at 14:45
  • `Object o = "string"` performs type erasure, you've force the `String` to be considered a generic `Object`. Passing `o` to `m1()` uses the object version because that is the type of the variable `o`. – Michael Shopsin Nov 30 '15 at 15:11

1 Answers1

3

The decision is made at compile-time, based on the type of the expression being passed in. So

  • m1("string") uses the String version (since the literal is of type String)

  • m1(new String("string")) uses the String version since the expression new String("string") is of type String

  • All three of your m1(o) ones use the Object version because the type of o is Object (per the declaration)

Again for emphasis, the concrete type of what o refers to doesn't matter, it's the static type of the expression that the compiler uses to determine which overload to call.

And that means if you change the type of the expression, you can make the compiler make a different choice:

Object o = "string";
m1((String)o); // Calls the String version

There's an entire section of the JLS dedicated to method invocation expressions: §15.12: Method Invocation Expressions. The relevant subsection is §15.12.2: Compile-Time Step 2: Determine Method Signature.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875