Static and Dynamic Binding in Java

Data Binding in Java

The relation between a class and method or class and field is known as Data Binding.

Static and Dynamic Binding in Java- TutorialandExample.com

In Java, we can create a class for Student_info, but until we link up the class with variables, methods, and constructors, it is just a class. Let’s say we add variables for student_name, course, age, etc. when we create a new instance to the Student_info class and access the class variable, these items are bound together. This process is called Data Binding.

Types of Data Binding in Java

There are two types of Data Binding.

  • Static Binding
  • Dynamic Binding

Static Binding in Java

It’s a compile-time Binding. When we call a method, Java binds fields and method with classes at the compile time. It can be also called as the Early Binding.

Let’s look at our Student_info class again.

Output

Because the method Info() is static, it means the method belongs to class itself. If we create many instances for Student_info, we only reference the fields and methods for one time. So if we declare a method with keyword static, final or private, binding is going to be static.

Dynamic Binding in Java

It’s a runtime Binding. It occurs at runtime because Java would not know which method or field to reference at compile time. In Dynamic binding, the type of the object is determined at run time.

One perfect example of dynamic binding is method overriding as in overriding both parent and child classes have the same method, and in this case, the object type determines which method is to be executed. The object type determined at the run time so this is known as dynamic binding.

It can also be called as the Late Binding.

Let’s have a look at the below example

Output

In the above example, the compiler cannot determine the object type, because the instance of Student_info is also an instance of College_info.  So compiler does not know its base type.