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”.
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:
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).
Let’s combine inheritance and overriding in a simple program.
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:
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.