This article is intended to analyze the mechanism of method overload in the Java language through a test topic to help readers can better master the basics of Java language.
First, let's take a test topic first, the source code is as follows, can you think the program can be compiled? If you can use the result of the compilation output? //TestoverLoad.javapublic class testoverload {public static void main (string [] args) {test test = new test (); test.print (null);}}
Class test {
Public void print (String Some) {system.out.println ("String Version Print"); public void print (Object Some) {system.out.println ("Object Version Print");}
}
The answer can be compiled, the result of the output is String Version Print. I don't know if you guess whether it is accurate to know the principles, this topic is obviously overloaded by the method, and overloading the Java class can have a plurality of method names. The compiler can distinguish them through the type and number of methods. The return value and exception cannot be used as a distinction. The above program outputs String Version Print is the principle of compliance with the accuracy of the method overload. NULL is transmitted to method print () as a very special parameter, because you can think that null is String, or you can think that null is Object . But from the hierarchy, Object is in the upper layer, String is inherited from Object, calling Print (String Some) will be more accurate.
If you add a method in the TestoverLoad class, how would this? Public class testoverload {public static void main (string [] args) {test test = new test (); test.print (null);}}
Class test {
public void print (String some) {System.out.println ( "String version print");} public void print (Object some) {System.out.println ( "Object version print");} public void print (StringBuffer some ) {System.out.println ("StringBuffer Version Print");}} The answer cannot be compiled, why? Since StringBuffer and String have no inheritance, the compiler feels that StringBuffer and String are very accurate, it doesn't know which method is running, so it will make compilation errors, this is the method overload The principle of uniqueness. If we modify the parameter null to "Hello World", you can compile and run the String Version Print.