Java 是否有任何理由对同一类中的重载方法使用后期/静态绑定?

2022-01-24 00:00:00 polymorphism 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.

相关文章