Method overriding forms the basis for one of Javas most powerful concept called Dynamic Method Dispatch .Which is the mechanism by which a call to an overridden method is resoled at runtime rather than at compile time.Dynamic Method Dispatch shows how Java implements runtime polymorphism.A superclass reference to a subclass object.Java uses this concept of act to resolve the calls to overridden methods at runtime.When an overridden method is called through a superclass reference , Java determines which version of that method to execute based upon the type of the object being referred to at the time call occurs.Thus this determination is made at runtime, that is it is the type of the object being referred to that determines which version of an overridden method will be execute.
class A
{
void CallMe( )
{
System.out.println( "Inside A's CallMe method !" );
}
}
class B extends A
class A
{
void CallMe( )
{
System.out.println( "Inside A's CallMe method !" );
}
}
class B extends A
{
void CallMe( )
{
System.out.println( "Inside B's CallMe method !" );
}
}
class C extends B
{
void CallMe( )
{
System.out.println( "Inside C's CallMe method !" );
}
}
class MethodDispatch
{
public static void main(String args[ ])
{
A a = new A( );//object of A
B a = new A( );//object of B
C a = new A( );//object of C
A r;
r.CallMe( );
r = b;//referred to B's object
r.CallMe( );
r = c;//referred to C's object
r.CallMe( );
}
}
OUTPUT
Inside A's CallMe method
Inside B's CallMe method
Inside C's CallMe method
No comments:
Post a Comment