Is there any reason that Java uses late/static binding for overloaded methods in the same class?(Java 是否有任何理由对同一类中的重载方法使用后期/静态绑定?)
问题描述
Java 对重载方法使用早期绑定有什么具体原因吗?难道不能为此使用后期绑定吗?
Is there any specific reason why Java uses early binding for overloaded methods? Wouldn't it be possible to use late binding for this?
例子:
public class SomeClass {
public void doSomething(Integer i) {
System.out.println("INTEGER");
}
public void doSomething(Object o) {
System.out.println("OBJECT");
}
public static void main (String[] args) {
Object i = new Integer(2);
Object o = new Object();
SomeClass sc = new SomeClass();
sc.doSomething(i);
sc.doSomething(o);
}
}
打印:OBJECT OBJECT
Prints: OBJECT OBJECT
我宁愿期待:整数对象
推荐答案
在我看来,最明显的原因是它允许编译器保证确实会有一个函数被调用.
It seems to me that the most obvious reason is that it allows the compiler to guarantee that there will actually be a function to be called.
假设 Java 根据运行时类型选择函数,而你写了这个:
Suppose Java chose the function based on the run-time type, and you wrote this:
public class MyClass
{
public void foo(Integer i)
{
System.out.println("Integer");
}
public void foo(String s)
{
System.out.println("String");
}
public static void main(String[] args)
{
Object o1=new String("Hello world");
foo(o1);
Object o2=new Double(42);
foo(o2);
}
}
输出是什么?对 foo 的第一次调用可能会打印String",但第二次调用无处可去.我想它可能会产生运行时错误.这类似于严格类型与松散类型的争论.如果它在运行时选择该函数,它在某种意义上可能更灵活.但是通过在编译时选择函数,我们可以在编译时收到错误消息,而不必等到运行时,并确保我们已经对每个相关的数据组合进行了所有可能的路径.
What's the output? The first call to foo presumably prints "String", but the second call has nowhere to go. I suppose it could generate a run-time error. This is similar to the argument of strictly-typed versus loosely-typed. If it chose the function at run time, it could be more flexible in some sense. But by choosing the function at compile time, we get the error messages at compile time rather than having to wait until run time and be sure that we have exercised every possible path with every relevant combination of data.
这篇关于Java 是否有任何理由对同一类中的重载方法使用后期/静态绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 是否有任何理由对同一类中的重载方法使用后期/静态绑定?
基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
