Dynamic Method Dispatch In Java Example

Chapter: Inheritance Last Updated: 19-06-2016 19:44:59 UTC

Program:

            /* ............... START ............... */
                
class A {
	void callme() {
		System.out.println("Inside A's callme method");
	}
}

class B extends A {
	void callme() // override callme()
	{
		System.out.println("Inside B's callme method");
	}
}

class C extends A {
	void callme() // override callme()
	{
		System.out.println("Inside C's callme method");
	}
}

public class JavaDynamicMethodDispatchExample {

	public static void main(String args[]) {
		A a = new A(); // object of type A
		B b = new B(); // object of type B
		C c = new C(); // object of type C
		A r; // obtain a reference of type A
		r = a; // r refers to an A object
		r.callme(); // calls A's version of callme
		r = b; // r refers to a B object
		r.callme(); // calls B's version of callme
		r = c; // r refers to a C object
		r.callme(); // calls C's version of callme
	}
}
                /* ............... END ............... */
        

Output

Inside A's callme method
Inside B's callme method
Inside C's callme method

Notes:

  • Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime.

Tags

Dynamic Method Dispatch, Java

Similar Programs Chapter Last Updated
Java Final Class Inheritance 02-08-2017
Java Final Method In Inheritance Inheritance 02-08-2017
Java Multilevel Hierarchical Inheritance Inheritance 01-08-2017
Java Super To Invoke Parent Class Method Inheritance 31-07-2017
Java Super To Invoke Parent Class Constructor Inheritance 30-07-2017
Static And Dynamic Binding In Java Inheritance 24-03-2017
Java Overloaded Method To Print Array Inheritance 03-09-2016
Abstract Class In Java Example Inheritance 20-07-2016
Method Overriding In Java Example Inheritance 20-07-2016
Method Overloading In Java Example Inheritance 20-07-2016
Inheritance And Constructors In Java Inheritance 20-07-2016
Multilevel Inheritance In Java Example Inheritance 22-09-2018
Super() In Java Example Inheritance 14-07-2016
Inheritance In Java Example Inheritance 20-07-2016

1