gpt4 book ai didi

java - 子类型多态性 : Always late binding?

转载 作者:行者123 更新时间:2023-11-29 04:58:01 24 4
gpt4 key购买 nike

This维基百科指出:

Since the specific type of a polymorphic object is not known before runtime (in general), the executed function is dynamically bound. Take, for example, the following Java code:

 public void foo(java.util.List<String> list) {
list.add("bar");
}

List is an interface, so list must refer to a subtype of it. Is it a reference to a LinkedList, an ArrayList, or some other subtype of List? The actual method referenced by add is not known until runtime.

考虑这个例子:

List<String> list;

list = new LinkedList<String>();
foo(list);

list = new ArrayList<String>();
foo(list);

为什么直到运行时才知道这里引用的实际方法?难道编译器不能只检查对象 list 分配给哪种类型的 foo 的每次调用?当然,这只有在程序是确定性的并且不涉及随机性(例如用户交互)时才有可能。

这是引用语句中(一般)的意思还是我的理解有误?

在程序是确定性的特殊情况下,是使用静态绑定(bind)还是 - 在 Java 中 - 总是使用动态绑定(bind),而不管可能发生什么?如果是,为什么?

最佳答案

该声明针对的是一般情况。仅给出 Wikipedia 示例的代码,无法判断 list 参数的具体类型。在您的示例中,可以说出具体类型。

如果 Java 运行时能够检测到变量的具体类型,则它实际上会去虚拟化方法调用。

如果您对该主题感兴趣:这是一个link讨论去虚拟化技术的论文。

关于java - 子类型多态性 : Always late binding?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33063160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com