Binding ใน Java
Binding = การเชื่อมโยงระหว่าง method call และ implementation จริง
Static Binding (Early Binding)
- Resolve ที่ compile time
- ใช้ type ของ class/fields ในการ resolve
- ตัวอย่าง: Method Overloading
- Methods: private, final, static
Dynamic Binding (Late Binding)
- Resolve ที่ runtime
- ใช้ object จริงในการ resolve
- ตัวอย่าง: Method Overriding
- Methods: virtual methods (non-static, non-final, non-private)
ตารางเปรียบเทียบ
| Key | Static Binding | Dynamic Binding |
|---|---|---|
| Resolve Time | Compile time | Runtime |
| Resolve Mechanism | Type of class/fields | Actual object |
| Example | Overloading | Overriding |
| Method Types | private, final, static | Virtual methods |
ตัวอย่าง
public class FastFood {
public void create() {
System.out.println("Creating in FastFood class");
}
}
public class Pizza extends FastFood {
public void create() {
System.out.println("Creating in Pizza class");
}
}
public class Main {
public static void main(String[] args) {
FastFood fastFood = new FastFood();
fastFood.create(); // Static binding (FastFood.create)
FastFood pza = new Pizza();
pza.create(); // Dynamic binding (Pizza.create)
}
}
สรุป
Static binding เร็วกว่า (resolve ตอน compile) แต่ dynamic binding ให้ polymorphism จริงได้ (resolve ตอน runtime ตาม object จริง)