1 Public classTestnull {2 Public voidmethod (Object o) {3System.out.println ("Object Version");4 }5 6 Public voidmethod (String s) {7System.out.println ("String Version");8 }9 Ten Public Static voidMain (string[] args) { OneTestnull tn=Newtestnull (); ATn.method (NULL); - } - the}
The compilation can pass, and the result is as follows:
So, how exactly does null call a function when it is a parameter? Before you answer this question, let's look at other examples.
Public classTESTCALLMETHOD2 {voidTest (object s) {System.out.println ("object Version");} voidTest (TestCallMethod2 t) {System.out.println ("TESTCALLMETHOD2 version");} voidTest (SubTestCallMthod2 t) {System.out.println ("Subtestcallmethod version");} //void Test (string s) {System.out.println ("string version");} Public Static voidMain (string[] args) {TestCallMethod2 T=NewTestCallMethod2 (); T.test (NULL); T.test (NewObject ()); }}classSubTestCallMthod2extendstestcallmethod2{}
The above code can be known, 4 test () function, when null as an argument to call, according to the inheritance of the relationship, the lowest subclass of the test () function, when the fourth Test () method is not annotated, A compilation error occurs because the string type and TestCallMethod2 two are similar to the object subclass, and the test () method of the sibling class exists.
How does the Java compiler call a function when NULL is a parameter?