Method Overriding In Java

Introduction

 
In this article, I am describing the feature of overriding in Java. Students and junior developers know the concept of overriding but they have less of an idea of how to implement it practically and in projects. Today, I am discussing a real-world scenario; first I am giving the concept of overriding and then I will share the real-world scenario.
  

What is overriding?

  • Overriding is basically the concept in which the parent class has the function with the same name, parameter and return type defined in subclass; this is known as overriding.
     
  • It is mandatory that the method name, parameter and return type of function are the same.
     
  • Now sub class is fully responsible that it reimplements the function according to your requirements.
Points to Remember?
  • Private method can't override
  • Static member can't override
  • Final keyword can't override
  • Constructor method can't override
  • The return type should be the same in all sub classes which is declared in super class.
Real-World Example of Overriding
  • Consider a scenario, KFC Hotel is a class that provides the functionality to get rates. But the rate varies according to countries. For example, KFC Hotel Dubai, KFC Hotel India and KFC Hotel America could provide a burger at an $80, $70 and $90 rate.
     
    Overriding
     
  • Now you see that if we declare the method with name rate() right, we declare it into three classes and if we pass the different signature for assuming polymorphism concept that is also wrong because we have only one signature, which is an integer, and the datatype is also the same in three functions.
Sow how do we solve the Problem?
  • Now the overriding concept comes in as I already told you when the function name, parameter and return remains the same as is declared in super class but in sub class you are fully responsible to re-implement these methods according to your choice.
     
    Now open the Eclipse IDE and create a simple java project and add the class. In class declare the three classes and add three methods which have the same name, parameter and return type. You see that the green arrow type appears and this indicates that these methods are overridden.
     
    code
     
    Now move to the main program, and make three instances of a class and then print out these three instances with their method name. This is a GIF image in which you can see both class and Main program in an animation mood.
     
    program
     
In the bottom you see the result, now, in my opinion, the concept of Overriding is now clearer and you understand it better. This is the conclusion of this article.
Read more articles on Java