4

I am unable to understand why this program prints String

class AA {

    void m1(Object o) {
        System.out.println("Object ");
    }

    void m1(String o) {
        System.out.println("String ");
    }
}

public class StringOrObject {

    public static void main(String[] args) {
        AA a = new AA();
        a.m1(null);
    }
}

Please help me to understand how this works to print Sting rather than Object

Cœur
  • 34,719
  • 24
  • 185
  • 251
lowLatency
  • 5,266
  • 11
  • 41
  • 64

2 Answers2

3

Dave Newton's comment is correct. The call to the method goes to the most specific possible implementation. Another example would be:

class Foo {}
class Bar extends Foo {}
class Biz extends Bar {}


public class Main {

    private static void meth(Foo f) {
        System.out.println("Foo");
    }

    private static void meth(Bar b) {
        System.out.println("Bar");
    }

    private static void meth(Biz b) {
        System.out.println("Biz");
    }


    public static void main(String[] args) {
        meth(null); // Biz will be printed
    }
}
Ernest Friedman-Hill
  • 79,064
  • 10
  • 147
  • 183
Emil H
  • 18,501
  • 3
  • 41
  • 63
0

This will try and make the most specific call. Subclass object gets the preference which is String in this case.

roger_that
  • 9,063
  • 18
  • 58
  • 96