Saturday, June 9, 2007

Dynamic Method Dispatch in Java

The sub classes object can be assigned to a super classes reference. This reference can in turn access the methods of the sub class. But the sub class reference cannot hold the super class's object. This is known as Dynamic Method Dispatching in Java.
A small example code is given below...

 class A {  
A() {
System.out.println("Constructor of Class A");
}
void show() {
System.out.println("I m in Class A");
}
}

class B extends A {
B() {
System.out.println("Constructor of Class B");
}
void show() {
System.out.println("I m in Class B");
}
}

public class DynamicMethodDispatch {
public static void main(String a[]) {
A aobj;
aobj = new A();
aobj.show();
aobj = new B();
aobj.show();
}
}


Output:

Constructor of Class A
I m in Class A
Constructor of Class A
Constructor of Class B
I m in Class B

No comments: