DYNAMIC BINDING

“Dynamic” means “run time” and “binding” means “association”. 

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

NOTE:In dynamic binding, the method call is bonded to the method body at runtime. This is also known as late binding. 

Rules Regarding Dynamic Binding:

  • Methods or functions of child and parent class must have the same name.
  • Methods or functions of child and parent class must have the same parameter.
  • Inheritance relationship is mandatory (IS-A relationship).

Sample Program:

COMPUTER PROGRAM:

public class Computer
{
public static void main(String[]args)
{

}
public void identify1()
{
System.out.println(“This Is Computer”);
}
public void identify2()
{
System.out.println(“Computer Speaker”);
}
}

LAPTOP PROGRAM:

public class Laptop extends Computer
{
public static void main(String[]args)
{
Computer user = new Laptop();
Laptop l = new Laptop();
l.identify1();
l.identify2();
l.identify3();
//user.identify1();
//user.identify2();
//user.identify3();
}
public void identify1()
{
System.out.println(“This Is Laptop”);
}
public void identify2()
{
System.out.println(“Laptop Speaker”);
}
public void identify3()
{
System.out.println(“COOLING PAD”);
}
}

OUTPUT:

  • c:\java>javac -d . Computer.java
  • c:\java>javac -d . Laptop.java
    Laptop.java:8: error: cannot find symbol
    user.identify3();
    ^
    symbol: method identify3()
    location: variable user of type Computer
    1 error
  • c:\java>javac -d . Laptop.java
  • c:\java>java Laptop
    This Is Laptop
    Laptop Speaker
  • c:\java>javac -d . Laptop.java
  • c:\java>java Laptop
    This Is Laptop
    Laptop Speaker
    COOLING PAD
  • c:\java>

Leave a comment

Design a site like this with WordPress.com
Get started