Binding(Static and Dynamic) in java

Binding is process of resolving a method class to find out its body.

  There are two types of binding

  1) static binding/early binding : Whenever a method call is resolved at the compile time then it is known as static binding/early binding.

  2) dynamic binding /late binding: Whenever a method call is resolved at the execution time then it is known as dynamic binding/late binding.


Example of static binding

Method Overloading is best example of static binding.

class Example {
	// sum method for summing two number
	public void sum(int a, int b) {
		int c = a + b;
		System.out.println("sum = " + c);
	}

	// sum of 3 int type numbers
	public void sum(int a, int b, int c) {
		int x = a + b + c;
		System.out.println("sum = " + x);
	}

	// define main method
	public static void main(String[] args) {
		Example ex = new Example();
		ex.sum(2, 3);
		ex.sum(1, 2, 33);	
	}
}
sum = 5
sum = 36

Example of dynamic binding

Method Overriding(dynamic method dispatch) is best example of dynamic binding.

// example of method overriding
class A {
	int i, j;
	A(int a, int b) {
		i = a;
		j = b;
	}
	// print i and j
	void display() {
		System.out.println("value of i =" + i);
		System.out.println("value of j =" + j);
	}
}

class B extends A {
	int p;

	B(int a, int b, int c) {
		super(a, b);
		p = c;
	}
	// print p
	// this method overrides display() of Parent class(A)
	void display() {
		System.out.println("value of p= " + p);
	}
}
public class Example {
	public static void main(String[] args) {
		B b = new B(2, 4, 5);
		b.display();// this class display() of B
	}
}
value of p= 5

Rules to find out type of Binding(static or dynamic)

Following rules are used to find out type of binding to resolve a method call.

  static methods are always statically binded.

  Call to a constructor is always statically binded.

  Call to a private non-static method is always statically binded.

  Call to a non-private , non-static method with super keyword is always statically binded.

  Call to a rest of non -static method is always dynamic binded.