什麼是 Java 中的繫結?
在 Java 中,方法呼叫與方法體間的關聯稱為繫結。有兩種繫結。
靜態繫結
在靜態繫結中,方法呼叫在編譯時與方法體繫結。這也被稱為早期繫結。這使用靜態的、私有的和最終方法來完成。
示例
class Super{ public static void sample(){ System.out.println("This is the method of super class"); } } Public class Sub extends Super{ Public static void sample(){ System.out.println("This is the method of sub class"); } Public static void main(String args[]){ Sub.sample() } }
輸出
This is the method of sub class
動態繫結
在動態繫結中,方法呼叫在執行時與方法體繫結。這也被稱為後期繫結。這使用例項方法來完成。
示例
class Super{ public void sample(){ System.out.println("This is the method of super class"); } } Public class extends Super{ Public static void sample(){ System.out.println("This is the method of sub class"); } Public static void main(String args[]){ new Sub().sample() } }
輸出
This is the method of sub class
廣告