Java中的编译时多态和运行时多态有什么区别?
如果我们使用实例方法执行(实现)方法重写和方法重载,则它是运行时(动态)多态性。
在动态多态中,方法调用和方法主体之间的绑定是在执行时发生的,这种绑定称为动态绑定或后期绑定。
示例
class SuperClass{
public static void sample(){
System.out.println("Method of the super class");
}
}
public class RuntimePolymorphism extends SuperClass {
public static void sample(){
System.out.println("Method of the sub class");
}
public static void main(String args[]){
SuperClass obj1 = new RuntimePolymorphism();
RuntimePolymorphism obj2 = new RuntimePolymorphism();
obj1.sample();
obj2.sample();
}
}输出结果
Method of the super class Method of the sub class
如果我们使用静态,私有,最终方法执行(实现)方法重写和方法重载,则这就是编译时(静态)多态性。
在静态多态性中,方法主体之间的绑定是在编译时发生的,这种绑定称为静态绑定或早期绑定。
示例
class SuperClass{
public static void sample(){
System.out.println("Method of the super class");
}
}
public class SubClass extends SuperClas {
public static void sample(){
System.out.println("Method of the sub class");
}
public static void main(String args[]){
SuperClass.sample();
SubClass.sample();
}
}输出结果
Method of the super class Method of the sub class
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短