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
  • 37,241
  • 25
  • 195
  • 267
lowLatency
  • 5,534
  • 12
  • 44
  • 70

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
  • 80,601
  • 10
  • 150
  • 186
Emil L
  • 20,219
  • 3
  • 44
  • 65
0

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

roger_that
  • 9,493
  • 18
  • 66
  • 102