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
如果我们使用静态、私有、final 方法执行(实现)方法覆盖和方法重载,则为编译时(静态)多态性。
在静态多态性中,方法调用和方法体之间的绑定发生在编译时,这种绑定称为静态绑定或早期绑定。
示例
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP