Friday, 19 December 2014

What is static and dynamic binding in java

Binding in Java:

Connecting a method call(calling nethod) to a method body(of that calling method)  is called binding.

It can be of two types:

>1.static binding (early binding).
>2.dynamic binding (late binding).

What is type in Java ?

>1.variables have a type

For example:int age=26;  here age variable is a type of int.

>2.References have a type

For example:

class Test{
public static void main(String []args){
Dog d1;
    }
}

Here d1 is a type of  Dog.

>3.Objects have a type

An object is an instance of particular java class,but it is also an instance of its superclass.

For example:

class Person {  }
class Student extends Person{

public static void main(String []args){
Student s1=new Student();
  }
}

Here s1 is an instance of Student class,but it is also an instance of Person.

>1. static binding:

When type of the object is determined at compiled time(by the compiler), it is known as static binding. If there is any private, final or static method in a class,it is static binding.

Example of static binding:

class Test{
private void run()  { System.out.println("test is running");}

public static void main(String []args){
Test t1=new Test();
t1.run();
  }
}


>2.dynamic binding:

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding:

class Person{
void run()  { System.out.println("person is running");}
}
class Studet extends Person{
void run()  {  System.out.println("student is playing");}

public static void main(String []args){
Person p=new Student();
p.play();
   }
}

Output:  student is playing

Note:In the above example object type cannot be determined by the compiler,because the instance of Dog is also an instance of Animal.So compiler doesn't know its type,  only its base type.  



1 comment :

  1. Great work of using dynamic and static binding in Java programming by illustrating various example to provide ease to the readers. I think this is best work on this topic.

    ReplyDelete