Polymorphism is one of the core principles of Object-Oriented Programming (OOP) in Java. It allows objects to take multiple forms, enabling more flexible and maintainable code. A fundamental concept within polymorphism is binding, which determines how method calls are resolved during execution. Java supports two types of binding: Static Binding (Early Binding) and Dynamic Binding (Late Binding).
Static Binding (Early Binding)
Static binding occurs when the method to be executed is determined at compile time. It is associated with methods that are final, static, or private, as these methods cannot be overridden in subclasses.
Since the method is resolved at compile time, the Java compiler determines the method call based on the reference type rather than the actual object type.
Example of Static Binding:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class StaticBindingExample { static void display() { System.out.println("Static Binding: This is a static method."); } private void show() { System.out.println("Static Binding: This is a private method."); } public static void main(String[] args) { StaticBindingExample obj = new StaticBindingExample(); obj.display(); obj.show(); } } |
Dynamic Binding (Late Binding)
Dynamic binding occurs when the method to be executed is determined at runtime. It is associated with method overriding, where a subclass provides a specific implementation of a method already defined in the parent class.
Here, the method call is resolved based on the actual object type at runtime, allowing Java to determine the correct method implementation dynamically.
Example of Dynamic Binding:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Parent { void show() { System.out.println("Dynamic Binding: Parent's show method."); } } class Child extends Parent { @Override void show() { System.out.println("Dynamic Binding: Child's show method."); } } public class DynamicBindingExample { public static void main(String[] args) { Parent obj = new Child(); // Upcasting obj.show(); // Calls Child's show method at runtime } } |
Static vs. Dynamic Binding
Feature | Static Binding | Dynamic Binding |
---|---|---|
Resolution Time | Compile time | Runtime |
Methods Used | static, final, private | Overridden methods |
Flexibility | Less flexible | More flexible |
Performance | Faster | Slightly slower |
Determined By | Reference Type | Object Type |