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