经过2-3个小时才知道, compile-time and run-time 有什么区别 . 最后,我想出了这个 .
在运行时分配的内存称为运行时/动态绑定,并在编译时分配,称为编译时/静态绑定 .
然后我尝试了这个例子
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();
被认为是运行时绑定 . 既然, a
是 myclass
的对象,但突然编译器发现,类错误匹配 . 因此,它将动态绑定 thisclass
对象的空间 .
所以,直到这里,我得到了东西 . 但是,我发现,另一个常见的答案是 overloading refer to compile time and overriding refer to run-time . 我没有明白这一点 .
thisclass a= new thisclass();
a.here();
这也称为运行时绑定 . ??如果在这里写错了,请纠正我 .
3 回答
首先,内存分配不在此图中 . 没有编译时内存分配 .
这个问题将编译时与静态绑定和运行时与动态绑定混为一谈 .
静态绑定在编译时发生;动态绑定在运行时发生 .
现在,当你写作
在编译时发生的是方法签名的解析:你正在调用
here(int)
并且该选择是最终的 . 这被称为"static binding" . 在运行时发生的是方法分派:运行时选择适合m
引用的对象的运行时类型的here(int)
实现 . 有两种方法可供选择:myclass.m(int)
和thisclass.m(int)
,运行时在此特定示例中选择后者 . 这被称为"dynamic binding" .关于你的问题"is overriding compulsory for dynamic binding" ... Java语言规范规定了选择在运行时调用的正确方法的规则 . 这些规则意味着一般情况下称为"dynamic binding"的程序 . 但是如果你在询问是否总是在运行时发生任何特定的进程,那么故事就不同了:优化的JIT编译器可以看到只有一种方法可供选择并输出"monomorphic call site",硬编码单选 . 此外,它还可以将整个方法内联到调用者中,从而甚至删除调用本身 .
这个:
不是运行时绑定,因为编译器知道要调用here()方法(来自thisclass的方法) . 但如果你愿意:
那么将是一个运行时绑定 .
P.S . :您的 class 名称应以大写字母开头 .
重载意味着在同一个类中具有多个具有不同参数的方法 . 调用哪个方法在编译时是已知的,因为此时指定了参数 .
覆盖意味着从子类中的父类重新定义方法 .