«Back to Home

Core Java

Topics

Dynamic And Static Binding In Java

Binding

In Java, binding means connection of the method definition to the method call.
 
In other words, related method calls the method body, which is called as a binding.
 
There are two types of binding in Java, which are,
  • Static binding

  • Dynamic binding
First, we discuss few terms, which is important to understand the concepts of binding.
 
Types of instance are,
  1. Variables type

    Every variable has a type primitive and non-primitive. Like
    1. Int n = 10// n variable is a type of int.  
  2. References type

    A reference type is a data type which based on a class rather than on one of the primitive types that are built in Java.
    1. class Student {  
    2.     public static void main(String args[]) {  
    3.             Student s; // s is a type of student class.  
  3. Object type

    An object is an instance of particular Java class and it is also an instance of its parent class.
    1. class Car {}  
    2. class Nano extends Car {  
    3.     public static void main(String args[]) {  
    4.             Nano n1 = new Nano(); // n1 is an instance of Nano class and also an instance of Car class.  
Static binding

In Java, when type of the object can be resolved at the compile time by the compiler, it is known as static or early binding.
 
If a class has any private, final or static method, there is static binding.
 
Let’s see an example, given below,
 
Code
  1. public class Toy {  
  2.     private void play() {  
  3.         System.out.println("toy is dancing");  
  4.     }  
  5.     public static void main(String args[]) {  
  6.         Toy t = new Toy();  
  7.         t.play();  
  8.     }  
  9. }  
1

Output

2

Dynamic binding

In Java, when type of the object can be resolved at runtime, it is known as a dynamic or late binding.
 
Let’s see an example, given below.
 
Code
  1. class Toy {  
  2.     void play() {  
  3.         System.out.println("Toy is dancing");  
  4.     }  
  5. }  
  6. public class Doll extends Toy {  
  7.     void play() {  
  8.         System.out.println("Doll is dancing and singing");  
  9.     }  
  10.   
  11.     public static void main(String args[]) {  
  12.         Toy t = new Doll();  
  13.         t.play();  
  14.     }  
  15. }  
3
 
Output

4

In the example, mentioned above, an object type can’t be resolved at a compile time by the compiler because instance of doll is also an instance of toy. Therefore, the compiler doesn’t know its type at the compile time. It knows only its base type.
 
Summary

Thus, we learnt that the related method calls the method body is called a binding in Java and also learnt its types of dynamic binding and static binding.