Java 是否有任何理由对同一类中的重载方法使用后期/静态绑定? [英] Is there any reason that Java uses late/static binding for overloaded methods in the same class?

查看:17
本文介绍了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 是否有任何理由对同一类中的重载方法使用后期/静态绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆