Java中的静态绑定与动态绑定
在Java中,静态绑定是指在编译时确定/知道对象类型的程序的执行,即,当编译器执行代码时,它知道对象的类型或对象所属的类。对象在运行时确定。
同样,静态绑定使用类的类型进行绑定,而动态绑定使用对象的类型,因为解析仅在运行时发生,因为对象仅在运行时创建,因此动态绑定的速度比静态绑定要慢。
由于私有,最终和静态修饰符绑定到类级别,因此方法和变量使用静态绑定并由编译器绑定,而其他方法则在运行时基于运行时对象进行绑定。
通常,我们可以说重载方法是使用静态绑定来绑定的,而重写方法是使用动态绑定来绑定的。
示例
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
public class StaticDynamicBinding {
public static void main(String[] args) {
Collection<String> col = new HashSet<>();
col.add("hello");
StaticDynamicBinding sdObj = new StaticDynamicBinding();
sdObj.print(col);
StaticDynamicBinding sdObj1 = new StaticDynamicBindingClass();
sdObj1.print(col);
}
void print(Collection<String> col) {
System.out.println("in collection method");
}
void print(HashSet<String> hs) {
System.out.println("in hashset method");
}
}
class StaticDynamicBindingClass extends StaticDynamicBinding {
void print(Collection<String> col) {
System.out.println("in collection method of child class");
}
}输出结果
in collection method in collection method of child class
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短