Depth - Why can not distinguish overloaded by return type?

Yesterday, the Internet shuffle, see a problem, very interesting.

Overload (same method name, different parameter list) this concept, I believe we all know, a lot of the interview will be asked.

But why can not distinguish overloaded by return type?

First overloading is a reflection of Java polymorphism, which implements a compile-time polymorphism.

for example:

max float (int A, int b);
int max (int A, int b);
the above two methods, when someone calls, do not return values directly is: max (...), you can distinguish it wants which function to call it?

When calling max (1, 2); the call can not be determined which, from a single point on, only to return a different value types that should not be allowed to overload.

In addition, the Java virtual machine also has problems mentioned overloaded:

In the "in-depth understanding of the Java Virtual Machine," in chapter 6.3.6 there is such a:

    In the Java language, to override a method, in addition to having the same name as the original simple method, but also it must have required a different method with the original signatures;

    Signature is a collection of various parameters in a method in the field of symbolic constant pool references, that is because the return value is not included in the signatures, so the Java language which can not rely solely on the different return value to an existing method overloading.

    However, in the Class file format, a larger number of signatures of the range, as long as the two descriptors are not exactly the same method may be coexist.

    That is, if the two methods have the same names and signatures, but the return values ​​are different, then the same also can be legally kept in a Class file.

Class file name the same method, the same parameters, return values ​​may be different, why not do it in Java files?

Because the provisions of the Java language specification, so there will be compile-time error.

Why Class files can it? Because different Java Virtual Machine Specification and the Java language specification, the two are separate ...

If more interested, you can read this article

The difference between the level of the Java language and the JVM level and method signatures of case study

Nonetheless limited level, dig dig no more .....
 

发布了393 篇原创文章 · 获赞 41 · 访问量 26万+

Guess you like

Origin blog.csdn.net/qq_32440951/article/details/88423815