See an interesting question
public class InvokeTest { public static void main(String[] args) { invoke(null); } // method_1 public static void invoke(Object obj) { System.out.println("Object obj"); } // method_2 public static void invoke(int[] arr) { System.out.println("int[] arr"); } // method_3 public static void invoke(int num) { System.out.println("int num"); }}What is the execution result?
My first reaction is that I cannot compile it. I have encountered a similar problem in my work before, that is, using invoke (object) null) or invoke (INT []) null) to determine which method to call.
However, the actual situation is not only through compilation, but also calling method_2
From the execution result, the JVM should match from the subclass. Find method_2 first, and then call it directly. For this reason, I have proved the following:
1. Add another method to the test class.
// method_4 public static void invoke(String str) { System.out.println("str"); }The result cannot be compiled.
2. added the test class:
public class Test {public static void main(String[] args) {invoke(null);}public static void invoke(Object obj) { System.out.println("Object obj");}public static void invoke(Object1 arr) { System.out.println("Object1");}public static void invoke(Object2 arr) { System.out.println("Object2");}public static void invoke(Ojbect3 str) { System.out.println("Ojbect3");}}class Object1 extends Object{}class Object2 extends Object1{};class Ojbect3 extends Object2{};The method can be correctly executed. The object3 method is called.
Conclusion: When null is used as a parameter to call a method, the JVM will match the method from the bottom to the top and execute it if it finds it. if a correct match is not found, a compilation error is reported. You must convert the value of null to the specified type to call the statement correctly.
Interesting questions about method Overloading