Static binding |
Dynamic binding |
- Static binding in Java occurs during compile time.
- private, final and static methods and variables use static binding and are bonded by compiler Must not have any explicit return type.
- Static binding uses Type information i.e. class in Java, for binding.
- Overloaded methods are bonded using static binding
|
- Dynamic binding occurs during runtime.
- virtual methods are bonded during runtime based upon runtime object.
- dynamic binding uses object to resolve binding.
- overridden methods are bonded using dynamic binding at runtime.
|
Example: Static Binding
public class Main {
void addNumbers(int num1, int num2){
System.out.println(num1 + num2);
}
void addNumbers(int num1, int num2, int num3){
System.out.println(num1 + num2 + num3);
}
public static void main(String args[]){
//creating Main class object
Main object = new Main();
//method call
object.addNumbers(10, 20);
object.addNumbers(20, 30, 40);
}
} |
public class Main {
void addNumbers(int num1, int num2){
System.out.println(num1 + num2);
}
void addNumbers(int num1, int num2, int num3){
System.out.println(num1 + num2 + num3);
}
public static void main(String args[]){
//creating Main class object
Main object = new Main();
//method call
object.addNumbers(10, 20);
object.addNumbers(20, 30, 40);
}
}
Output
Example: Dynamic Binding
class Test1{
void show(){
System.out.println("Inside show method of Test1 class");
}
}
public class Main extends Test1{
void show(){
System.out.println("Inside show method of Main class");
}
public static void main(String args[]){
//creating object
Test1 object = new Main();
//method call
object.show();
}
} |
class Test1{
void show(){
System.out.println("Inside show method of Test1 class");
}
}
public class Main extends Test1{
void show(){
System.out.println("Inside show method of Main class");
}
public static void main(String args[]){
//creating object
Test1 object = new Main();
//method call
object.show();
}
}
Output
Inside show method of Main class |
Inside show method of Main class