allthingsare🅿️.com Books ⬅️ Back allthingsare

“The Lord is my light and my salvation—whom shall I fear?”
[Psalm 27:1]


Method Overriding


12.2.1 What is Method Overriding?

Method Overriding is a key feature of inheritance in Java.
It means a child class can provide its own version of a method that it inherited from the parent class.

When you override a method:

  • The method name, return type, and parameter list must be exactly the same as the parent’s version.

  • When you call that method on a child object, the child’s version runs, not the parent’s.

Why override?
Overriding lets you customize or specialize behavior for the child class while still reusing the parent’s structure.


Example real life analogy:
Imagine you have a Vehicle class with a method move().
A Car extends Vehicle but might want move() to include specific details like “driving on roads”, while a Boat might override move() to mean “sailing on water”.


12.2.2 How to Override a Method

In Java, overriding is simple:

  • Write a method in the child class with the same signature as in the parent.

  • Add the @Override annotation — this is optional but highly recommended. It helps the compiler check that you really are overriding correctly.

Example:

java
public class Animal { void makeSound() { System.out.println("Some generic animal sound"); } } public class Dog extends Animal { @Override void makeSound() { System.out.println("Woof! Woof!"); } }

Key points:

  • Dog inherits makeSound() but overrides it to make it specific.

  • @Override helps you catch mistakes — if you accidentally change the method signature, the compiler will warn you.


Important:

  • The overriding method cannot reduce the visibility. For example, you can’t override a public method as protected.

  • You can increase visibility, but not reduce it.

  • The return type must be the same (or a subtype, which is called covariant return).


12.2.3 Mini Lab: Overriding in Action

Let’s combine inheritance and overriding in a simple program.

java
public class Animal { void makeSound() { System.out.println("Some generic animal sound"); } } public class Dog extends Animal { @Override void makeSound() { System.out.println("Woof! Woof!"); } public static void main(String[] args) { Animal a = new Animal(); Dog d = new Dog(); a.makeSound(); // Parent version d.makeSound(); // Overridden version } }

What happens here?

  • a is an Animal, so makeSound() prints: Some generic animal sound

  • d is a Dog, so makeSound() prints: Woof! Woof!


Why is this powerful?
This lets you write general code that works with the parent class, but specific behavior will run for each child class.

Example:

java
Animal myAnimal = new Dog(); myAnimal.makeSound(); // Runs Dog’s version!

This is the core idea behind polymorphism — you can treat all animals the same way (Animal type) but get different results at runtime depending on the actual object.