Static binding occurs during compile time whereas, dynamic binding occurs during runtime
Private, final, and static methods use static binding while virtual methods use dynamic binding.
The static binding uses class information for binding while dynamic binding uses objects for binding
Overridden methods use dynamic binding at runtime while overloaded methods use static methods at compile time.
These examples might give you an idea about static and dynamic binding.
public class StaticBindingExample
{
public static void main(String args[])
{
Collection collection = new HashSet();
StaticBindingExample sbe = new StaticBindingExample();
sbe.sort(collection);
}
public Collection sort(Collection c)
{
System.out.println("Inside Collection sort method");
return c;
}
public Collection sort(HashSet hs)
{
System.out.println("Inside HashSet sort method");
return hs;
}
}
Output: Inside Collection sort method
class Animal{
void sound(){
System.out.println("Inside Animal class");
}
}
class Cat extends Animal{
@Override
void sound(){
System.out.println("Inside cat class");
}
}
public class DynamicBindExample
{
public static void main(String[] args) {
Animal animal=new Cat();
animal.sound();
}
}
Output: Inside cat class
Want to learn Java? Check out the Java course from Intellipaat.