Home > Java > Method Overriding in Java: – PART-2

Method Overriding in Java: – PART-2

 

Real example of Java Method Overriding:-

Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 5%, 6% and 7% rate of interest.

 Img01

 

Advantages of method overriding

  • The main advantage of method overriding is that the class can give its own specific implementation to the inherited method without even modifying the parent class(base class).
  • The benefit of overriding is ability to define a behavior that’s specific to the subclass type which means a subclass can implement a parent class method based on its requirement.

Method Overriding in dynamic method dispatch

Dynamic method dispatch is a technique which enables us to assign the base class reference to a child class object. As you can see in the below example that the base class reference is assigned to child class object.

Note: In dynamic method dispatch the object can call the overriding methods of child class and all the non-overridden methods of base class but it cannot call the methods which are newly declared in the child class. In the above example the object obj was able to call the disp()(overriding method) and abc()(non-overridden method of base class).

However if you try to call the xyz () method (which has been newly declared in Test class) [obj.xyz()] then it would give compilation error with the following message:

Main.java: error: cannot find symbol

     obj.xyz();

Problem: The method xyz() is undefined for the type ABC

 

…continued in the next article Method Overriding in Java: – PART-3

This Article is TAGGED in , , . BOOKMARK THE permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">