This article aims to analyze the method overloading mechanism in the Java language through a test question to help readers better master the basic knowledge of the Java language.
First, let's take a look at a test question. The source code is as follows. Do you think the program can be compiled? What will happen if it can be compiled and output?
// Testoverload. Java
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 ");
}
}
The answer is that it can be compiled and the output result is string version print. I don't know whether you know the exact principle or not. This topic is obviously about method overloading. Overloading allows Java classes to have multiple methods with the same method name. The compiler can distinguish them by the type and number of parameters of the method. The return value and exception cannot be used as a difference sign. The program above outputs string version print, which follows the principle of accuracy in method overloading. null is passed to the method print () as a very special parameter (), because you can consider null as a string or null as an object. However, in terms of hierarchy, the object is in the upper layer, and the string is inherited from the object. Calling print (string some) is more accurate.
What if I add another method to the testoverload class as follows?
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 is that it cannot be compiled. Why? Because stringbuffer and string do not have an inherited relationship, the compiler feels that the stringbuffer and string methods as parameters are very accurate, and it does not know which method will be run at that time, therefore, a compilation error occurs. This is the principle of uniqueness in method overloading. If we change the null parameter to "Hello World", we can compile and run the output string version print.
I once read an article on java.sun.com saying that the return value of a method is also a sign of the difference between methods. In fact, this is wrong. Take a look at the following program
Public Class
{
Public int amethod (string S)
{
System. Out. println (s );
Return 1;
}
Public void amethod (string S)
{
System. Out. println (s );
}
}
During compilation, an error is prompted that the amethod (string s) method has been defined. Practice proves everything!