Static vs dynamic binding in java

            Static binding              Dynamic binding
  1. Static binding in Java occurs during compile time.
  2. private, final and static methods and variables use static binding and are bonded by compiler Must not have any explicit return type.
  3. Static binding uses Type information  i.e. class in Java, for binding.
  4. Overloaded methods are bonded using static binding
  1. Dynamic binding occurs during runtime.
  2. virtual methods are bonded during runtime based upon runtime object.
  3. dynamic binding uses object to resolve binding.
  4. overridden methods are bonded using dynamic binding at runtime.

Example: Static Binding

public class Main {
      void addNumbers(int num1, int num2){
            System.out.println(num1 + num2);
      }     
 
      void addNumbers(int num1, int num2, int num3){
            System.out.println(num1 + num2 + num3);
      }           
 
      public static void main(String args[]){
            //creating Main class object
            Main object = new Main();
            //method call
            object.addNumbers(10, 20);
            object.addNumbers(20, 30, 40);
      }
}

Output

30
90

Example: Dynamic Binding

class Test1{
    void show(){
        System.out.println("Inside show method of Test1 class");
    }
}
 
public class Main extends Test1{
      void show(){
        System.out.println("Inside show method of Main class");
      }        
 
      public static void main(String args[]){
            //creating object
            Test1 object = new Main();
            //method call
            object.show();
      }
}

Output

Inside show method of Main class