Dynamic method dispatch

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism.

Example

class Vehicle {
	void type() {
		System.out.println("Truck");
	}
}

class Car extends Vehicle {
	void type() {
		System.out.println("Car type");
	}
}

class Motorbike extends Vehicle {
	void type() {
		System.out.println("Bike");
	}
}

public class DynamicMethodDisplatch {
	public static void main(String[] args) {
		Vehicle v1 = new Vehicle();
		v1.type();
		Vehicle v2 = new Car(); // v2 referes to of type Car
		v2.type();
		Vehicle v3 = new Motorbike(); // v3 refers to type of Motorbike
		v3.type();
	}
}

Output

Truck
Car type
Bike