Pages

Thursday 18 April 2013

Differentiate between Early binding and late binding

Early binding means calling a non-virtual method that is decided at a compile time while Late binding refers to calling a virtual method that is decided at a runtime.

The polymorphism is achieved by early binding and late binding

Early Binding:

Compiler bind the objects to methods at the compile time.This is called early binding or static binding.Function overloading is example for early binding.

Late Binding:

Compiler bind the objects to methods at the runtime.This is called late binding or dynamic binding.Function overriding is example for late binding.


What is Dynamic Binding and static binding ?
Ans: Well Dynamic binding is objects are binded to the reference object on runtime where as static binding is the binding in which the compiler is straight away aware of which object is binded before runtime.
dynamic binding is also called late binding.
I have shown an example below which uses two classes  DynamicBinding and DBInherit  which inherits the DynamicBinding and overrides an method of the above class , so what happens if create a base class reference and initialise it with junior class object , then I will get the junior class method and not the base class method as it is overridden and the compiler knows it only at runtime.
Hence the output will show the junior class method output (DBInherit  is the junior class referred here) and not the base class.

DynamicBinding.cs class source code:

01. 
02. 
03.using System;
04.using System.Collections.Generic;
05.using System.Linq;
06.using System.Text;
07. 
08.namespace TestCsharp
09.{
10.class DynamicBinding
11.{
12.public virtual void abcd()
13.{
14.Console.Write("In base class\n");
15.}
16.}
17. 
18.class DBInherit : DynamicBinding // this is the junior class
19.{
20.public override void  abcd()
21.{
22.Console.Write("In junior class\n");
23.}
24. 
25.public void abcd2()
26.{
27.Console.Write("In junior class\n");
28.}
29.}
30.}
31. 
32. 
33. 



Program.cs class source code:
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05. 
06. 
07. 
08.namespace TestCsharp
09.{
10.class Program : InterfaceTest
11.{
12.static void Main(string[] args)
13.{
14.#region This code is used to show the dynamic binding
15. 
16.DynamicBinding _objDB = new DynamicBinding();
17._objDB.abcd();
18. 
19.DynamicBinding _objDB2 = new DBInherit(); ///this is an example of dynamic binding as the compiler did'nt knew if there is a method overriding the base class method
20._objDB2.abcd();
21. 
22. 
23.#endregion
24. 
25. 
26.}
27.}
28.}

The output will look like as shown below :


No comments:

Post a Comment