Method overriding lets a child class change how a method from its parent class works. This helps make programs flexible and clear.
0
0
Method overriding in Java
Introduction
When you want a child class to do something different from its parent for the same action.
When you have a general method in a parent class but need specific behavior in child classes.
When you want to reuse code but change only parts of it in child classes.
When implementing polymorphism to call child class methods through parent class references.
Syntax
Java
class Parent { void show() { // parent method code } } class Child extends Parent { @Override void show() { // child method code } }
The @Override annotation is optional but helps catch mistakes.
The method in the child must have the same name, return type, and parameters as in the parent.
Examples
The
Dog class changes the sound method to print "Dog barks" instead of the parent's message.Java
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } }
The
Car class overrides start to show a more specific message.Java
class Vehicle { void start() { System.out.println("Vehicle starts"); } } class Car extends Vehicle { @Override void start() { System.out.println("Car starts with a key"); } }
Sample Program
This program shows method overriding. The Child class changes the greet method. When we call greet on a Child object, it uses the child's version, even if the reference is of type Parent.
Java
class Parent { void greet() { System.out.println("Hello from Parent"); } } class Child extends Parent { @Override void greet() { System.out.println("Hello from Child"); } } public class Main { public static void main(String[] args) { Parent p = new Parent(); p.greet(); Child c = new Child(); c.greet(); Parent pc = new Child(); pc.greet(); } }
OutputSuccess
Important Notes
Method overriding only works with inheritance (child and parent classes).
The method signature must match exactly to override.
Using @Override helps the compiler check your code.
Summary
Method overriding lets child classes change parent class methods.
It helps customize behavior while keeping code organized.
Use @Override to avoid mistakes.