What is Method Overriding in Java: Simple Explanation and Example
method overriding happens when a subclass provides its own version of a method already defined in its superclass. This allows the subclass to change or extend the behavior of that method while keeping the same method name and parameters.How It Works
Imagine you have a basic recipe for making coffee in a cookbook (the superclass). Now, you want to make your own special coffee with extra ingredients, so you write your own recipe that uses the original but adds your twist (the subclass). In Java, method overriding works the same way: a subclass takes a method from its parent class and changes how it works.
When you call the method on an object, Java looks at the actual type of the object to decide which version of the method to run. This means if you have a coffee object of the special type, it will use the special recipe, not the basic one. This is called runtime polymorphism and helps programs be flexible and easy to extend.
Example
This example shows a superclass Animal with a method sound(). The subclass Dog overrides sound() to provide its own behavior.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Animal(); Animal myDog = new Dog(); myAnimal.sound(); // Calls Animal's sound myDog.sound(); // Calls Dog's overridden sound } }
When to Use
Use method overriding when you want a subclass to provide a specific behavior different from its superclass. This is common in real-world programs where you have a general class and many specialized versions.
For example, in a game, you might have a general Character class with a method attack(). Different characters like Wizard or Warrior can override attack() to perform unique attacks. This keeps your code organized and easy to maintain.
Key Points
- Method overriding requires the subclass method to have the same name, return type, and parameters as the superclass method.
- It enables runtime polymorphism, letting Java decide which method to call based on the object's actual type.
- The
@Overrideannotation helps catch mistakes and improves code readability. - Overriding allows customizing or extending behavior without changing the original class.