Java method overriding

Posted in Java By Raj On November 24, 2017

 

If you want to override any functionality or behavior of parent class in the child class then you can use java method overriding

Let me take a simple example, if you see the below diagram, the standard bike IS-A motorcycle, sports bike IS-A motorcycle and also scooter IS-A motorcycle all comes under motorcycle, here I am overriding applyBrake method which is in the scooter class because the functionality is different, you can not use foot pedal to apply brake in scooter what you use is either right lever or left lever

You need to consider below things before implementing java method overriding

  • You can not override private, static, and final methods
  • The method names should be same as whatever method in the parent class
  • The method parameters should be same as parent class method name

java-method-overriding

Example: Java method overriding

The below class is super class which is Motorcycle.java, the start method is final method which you cannot override in the child class

Childe class : Scooter.java

Test class: methodoverriding.java