Before developing a program for Overriding in Java let us first understand what overriding is. The fundamental concept of overriding is comes from a problem that arises while performing inheritance. In Java this problem is handled by using Dynamic Dispatcher. Now you will be thinking that I am telling you the solution for the problem but haven't yet told about what the problem exactly is. SO, Overriding is the problem that arises when both the base class and derived class in inheritance have a method with same same and the derived class overrides the body for the method.
Let us consider a example for this along with its solution or you can download a demo source code elaborating the concept of dynamic dispatcher in java from the link below : Download Source Code
Overriding.java
class Base {
 void show() {
  System.out.println("Base class show method is called");
 }
}
class DeriveClass extends Base {
 void show() {//show method is overridden 
  System.out.println("Derive class  show method is called");
 }
}
class DynamicDispatch {
 public static void main(String args[]) {
  Base bObj=new Base();
  DeriveClass dObj=new DeriveClass();
  Base ref;
  ref=bObj;
  ref.show();
  ref=dObj;
  ref.show();
 }
} 
In the above example as you can see there are two classes defined, one is the BaseClass and another is DeriveClass that is derived from the base class.
Both the classes share a common method called "show". Both the classes defined a body for this method.
There is another class named DynamicDispatch class.In this class I have created objects of both base class and derived class and created a reference of Base Class. By using which we have called the 'show' method of both base class and derived class using the same reference object. So the overriding issue in which the derived class show method overrides the base class show method is now solved by using the Dynamic Dispatcher.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.