1

In the following program:

public class PolyEx1 {
    public static void main(String[] args) {
    A refA = new A();
        refA.method1(null);
    }
}

class A {
    public void method1(Object o) {
        System.out.println("o");
    }

    public void method1(String str) {
        System.out.println("str");
    }
}

The output is "str", can someone explain me why str was printed? I am not able to understand this.

Simon Forsberg
  • 13,086
  • 10
  • 64
  • 108
prc
  • 43
  • 2

3 Answers3

2

As explained by Rohit here,

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.

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

However, if you have two methods with parameter - String, and Integer, then you would get ambiguity error for null, as compiler cannot decide which one is more specific, as they are non-covariant types.

As described in Section 15.12.5 of JLS

Community
  • 1
  • 1
Dark Knight
  • 8,218
  • 4
  • 39
  • 58
1

Java try to use the most specific applicable version of a method.

String extends Object and so the method using String as parameter is always called.

If you try to add a method that take an Integer input it will throws error as ambiguous methods, because String and Integer both of them are more specific than Object but none is more specific than the other one

Cirou
  • 1,420
  • 12
  • 18
0

public void method1(String str) will get executed because object is string supperclass so the string method will be called.

grepit
  • 21,260
  • 6
  • 105
  • 81