Method override passing null object

I can’t understand why this program prints a 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 understand how this works to print Sting, not Object

+4
source share
2 answers

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

 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 } } 
+3
source

This will try to make the most specific call. The subclass object takes preference, which in this case is a string.

0
source

Source: https://habr.com/ru/post/1481541/


All Articles