gpt4 book ai didi

java - 编译时间与运行时间

转载 作者:行者123 更新时间:2023-12-01 18:58:22 25 4
gpt4 key购买 nike

经过2-3个小时才知道,编译时和运行时有什么区别。最后,我想出了这个。

运行时分配的内存称为运行时/动态绑定(bind),编译时分配的内存称为编译时/静态绑定(bind)。

然后我尝试了这个例子

class myclass {

void here() {
System.out.println("Here from myclass !!");
}

void here(int i) {
System.out.println("Here !!" + i);
}
}

class thisclass extends myclass {

void here() {
System.out.println("Here from thisclass !!");
}
}

public class poly {

public static void main(String s[]) {
myclass m= new myclass();
myclass a= new thisclass();
m.here();
m.here(12);
a.here();
a.here(13);
}
}

所以,我还发现 myclass a= new thisclass(); 被认为是运行时绑定(bind)。因为,amyclass的对象,但是突然编译器发现,class不匹配。所以,它会动态绑定(bind)thisclass对象的空间。

所以,到这里,我已经拿到东西了。但是,我发现,另一个常见的答案是重载引用编译时和覆盖引用运行时。我没明白这一点。

thisclass a= new thisclass();
a.here();

这也称为运行时绑定(bind)吗? ??如果写的有什么不对的地方请指正。

最佳答案

首先,内存分配不在这张图中。没有编译时内存分配。

这个问题将编译时与静态绑定(bind)以及运行时与动态绑定(bind)混为一谈。

静态绑定(bind)发生在编译时;动态绑定(bind)发生在运行时。

现在,当你写

myclass m= new thisclass();
m.here(18);

编译时发生的是方法签名的解析:您正在调用here(int),并且该选择是最终的。这称为“静态绑定(bind)”。运行时发生的是方法dispatch:运行时选择适合于m引用的对象的运行时类型的here(int)实现。有两种方法可供选择:myclass.m(int)thisclass.m(int),在此特定示例中,运行时选择后者。这称为“动态绑定(bind)”。

至于你的问题“动态绑定(bind)是强制性的”...Java 语言规范规定了选择在运行时调用的正确方法的规则。这些规则意味着一般情况下称为“动态绑定(bind)”的过程。但是,如果您询问任何特定过程是否总是在运行时发生,情况就不同了:优化的 JIT 编译器可以看到只有一种方法可供选择,并输出一个“单态调用站点”,该调用站点对单个选择进行硬编码。此外,它还可以将整个方法内联到调用者中,从而甚至删除调用本身。

关于java - 编译时间与运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13232814/

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