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

查看:126
本文介绍了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); 
    } 
}

打印:对象对象

我宁愿期待:INTEGER OBJECT

I would rather expect: INTEGER 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天全站免登陆