Data Binding in Java
The relation between a class and method or class and field is known as Data Binding.
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.
public class Student_info
{
public static int roll_no;
public static string name;
public static string course;
}
Now we can create the objects and instances of Student_info and use these
variables and methods.
Student_info s1=new Student_info();
Student_info s2=new Student_info();
s1.roll_no=105;
s2.roll_no=106;
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.
public class Student_info
{
public static String name;
public static String course;
public static String Info( String n, String c)
{
name=n;
course=c;
return c;
}
public static void main(String[] args)
{
Student_info s1= new Student_info();
s1.Info("Alex", "B.tech");
System.out.println("Info: "+ name+ " " + course);
}}
Output
Info: Alex B.tech
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
class College_info{
void info(){
System.out.println("Getting college Info...");}
}
class Student_info extends College_info{
void info(){
System.out.println("Getting Students Info...");}
public static void main(String args[]){
College_info c=new Student_info();
c.info();
}
}
Output
Getting Students Info...
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.