Static binding and Dynamic binding
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, there is static binding.
Example:
class Test{
private void eat(){System.out.println("Dog is eating...");}
public static void main(String args[]){
Test d1=new Test(); //Here type of object(d1) Test is known to compiler.
d1.eat();
}
}
Output:
Dog is eating...
-------------------------------------------------------------------------------------------------------------------
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
In below example type of the object cannot be determined by the compiler, because the instance of Test is also an instance of Animal. So compiler doesn't know its type, at run time only it determines the type of object.
Example:
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Test extends Animal{
void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Test(); //Here type of the object is determined at run time.
a.eat();
}
}
Outpu:
dog is eating...
No comments:
Post a Comment