Static and Dynamic Binding in Java

Method binding in Java connects the method call to the method itself. Deciding which method to call can be compile-time (static) and runtime (dynamic).

There are two types of binding:

  1. Dynamic Binding (The type of the object is determined at run-time)
  2. Static Binding (Type of the object is determined at a compile-time)

Example of Dynamic Binding in Java

class Vehicle {
    
  public void move() {
    System.out.println("The vehicle is moving...");
  }
}

class Car extends Vehicle {
    
  public void move() {
    System.out.println("The car is moving...");
  }
}

class Test {
  
  public static void main(String[] args) {
    //variable of type Vehicle points to the object of its subclass Car
    Vehicle car = new Car();
    car.move();
  }
}
Output: The car is moving…

Here it is decided in runtime which method will be called, based on the object the variable of type Vehicle points. It uses the object reference to find which method to use.

Example of the Static Binding in Java

class Vehicle {
    
  public static void move() {
    System.out.println("The vehicle is moving...");
  }
}

class Car extends Vehicle {
    
  public static void move() {
    System.out.println("Car is moving...");
  }
}

class Test {
 
  public static void main(String[] args){
    Vehicle car = new Car();
    car.move();
  }
}
Output: The vehicle is moving…
 
Here, the superclass method is called because it is a static method, so it uses type (in this case, Vehicle) to resolve which static method to call.
 
This applies to private and final methods also.
 
That was all about method binding in Java. Proceed to the next lesson to learn more about Java instanceof operator.
 

Leave a Reply

Your email address will not be published.