🔸 What is Binding in Java?
Binding means linking a method call to the method definition. There are two types of binding in Java:
- Static Binding – happens at compile time
- Dynamic Binding – happens at runtime
🔸 What is Dynamic Binding?
- Dynamic Binding (or Late Binding) is when Java decides at runtime which method to call based on the actual object, not the reference type.
- Java where the method implementation to be executed is determined at runtime based on the actual object type, not just its declared type.
- This differs from static binding, where the method call is resolved at compile time
When and Why Use Dynamic Binding?
You should use it when:
✅ You want runtime polymorphism
✅ You are working with inheritance and method overriding
✅ You want your code to be flexible, reusable, and loosely coupled
Java Dynamic Binding
Dynamic binding refers to the process in which linking between method call and method implementation is resolved at run time (or, a process of calling an overridden method at run time). Dynamic binding is also known as run-time polymorphism or late binding. Dynamic binding uses objects to resolve binding.
Example:
package com.tutorialspoint;
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class Tester {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
// Dynamic Binding
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
Java Dynamic Binding: Using the super Keyword
When invoking a superclass version of an overridden method the super keyword is used so that we can utilize parent class method while using dynamic binding.
Example: Using the super Keyword
In this example, we've created two classes Animal and Dog where Dog class extends Animal class. Dog class overrides the move method of its super class Animal. But it calls parent move() method using super keyword so that both move methods are called when child method is called due to dynamic binding. In main() method, we're using Animal class reference and assign it an object of Dog class to check Dynamic binding effect.
Open Compiler
example:
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run
Top comments (0)