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

package com.keysandstrokes.examples.polymorphism;
public class Motorcycle {
	public Motorcycle() {
	}
	public void applyBrake() {
		System.out.println("root method");
	}
	public void changeBrake() {
	}
	public final void start() {
	}
}

Childe class : Scooter.java

package com.keysandstrokes.examples.polymorphism;
public class Scooter extends Motorcycle {
	@Override
	public void applyBrake() {
		// TODO Auto-generated method stub
		super.applyBrake();
		System.out.println("override brake functionality");
	}
}

Test class: methodoverriding.java

package com.keysandstrokes.examples.polymorphism;
public class Methodoverriding {
	public static void main(String[] args) {
		Scooter scooter = new Scooter();
		scooter.applyBrake();
	}
}

 

By coderss

Leave a Reply

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