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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP