Java 虚拟机是否允许重载返回类型?
我已经完成了这个 演示文稿.
Slide No:26 引用了那个
Slide No:26 quote that
Java language does not allow overloading on return type
Java Virtual machine does allow overloading on return type
这些说法是真的吗?如果两个陈述都成立,如何使代码可编译,以便 jvm 运行代码?
我有一个关于这个主题的 SE 问题:
I have one SE question on this topic :
Java - 为什么没有基于返回类型的方法重载?
提前致谢.
推荐答案
这些说法完全正确.
请记住,Java 是两件事——一是语言,二是虚拟机.虽然限制语言不允许基于类型的方法重载使 Java 成为一种更易于使用的语言,但 JVM 仍然可以允许这样做以使其更强大.
Remember that Java is two things - one,a language and two, a virtual machine. While restricting the language to not allow type based method overloading makes Java a simpler language to use, the JVM can still allow this to be done to make it more powerful.
作为一种语言,Java 有一个编译器,它强制执行使 Java 成为一种比允许这样做更简单、更容易的编程语言的规则.为此,它限制了您可以做什么,但仅限于 Java 语言本身.在 JVM 上运行 Scala 或 Ruby 之类的东西需要不同的规则和特性,在这个级别上,重要的是 JVM 具有灵活性,这使得 JVM 取得了如此巨大的成功,以至于它可以在如此多的平台和设备上找到.
As a language, Java has a compiler that enforces the rules that make Java a simpler, easier programming language than one that does allow this. To do this, it restricts what you can do, but only in the Java language itself. Running something like Scala or Ruby on the JVM requires different rules and features, and at this level it is important that the JVM allows the flexibility that has made the JVM such a big success that it is found on so many platforms and devices.
在一种可以通过返回类型重载的语言中,它很容易出错,不支持该功能的决定是故意使 Java 成为一种不易出错的编程语言.编译器如何知道您打算调用哪个函数?
In a language where overloading by return type is possible, it would be very error prone and the decision to not support that feature was deliberate to make Java a less error-prone programming language. How would the compiler know which function you intended to call?
另一方面,JVM 是一个低级、高度优化的虚拟机,它的存在是为了运行字节码,而不是 Java.因此,以这种方式限制 JVM 是不明智的,因为它应该能够运行根本不是从 Java 生成的字节码.
The JVM on the other hand is a low-level, highly optimised virtual machine that exists to run bytecode, not Java. It is therefore not wise to restrict the JVM in this fashion as it should be able to run bytecode not generated from Java at all.
另一个例子是多重继承,它在 Java 中不可用,但没有什么能阻止您编写支持多重继承的语言并将其编译为字节码.它会使您的语言更难使用,并且可能更容易出错,但如果您需要该功能,JVM 不会阻止您.
Another example would be multiple inheritance, which is not available in Java, yet nothing prevents you to write a language that supports multiple inheritance and have it compile to bytecode. It would make your language more difficult to use and potentially more error prone, but if you require that feature, the JVM will not stop you.
相关文章