Method Overriding in Java
Method overriding lets a subclass provide a specific implementation of a method that is already defined in its parent class. It is the foundation of runtime polymorphism in Java and a key principle of object-oriented design.
Key Features
Inheritance Based
Overriding requires an inheritance relationship.
Runtime Polymorphism
Java picks the right method at runtime by the actual object type.
Same Signature
Method name, parameters and return type (or covariant) must match.
@Override
Annotation that catches typos at compile time.
super Keyword
Calls the parent's version inside the override.
Final / Static
final and static methods cannot be overridden.
Syntax
- The parent class declares the method.
- The subclass redeclares it with the same name and parameters.
- Mark the subclass method with @Override.
- Use super.method() to call the parent version.
Override Rules
| Rule | Required | Note | Example |
|---|---|---|---|
| Same name | Yes | Identical name | show() |
| Same params | Yes | Type & order match | (int, String) |
| Return type | Same/Covariant | Can be subclass of original | Number → Integer |
| Access | ≥ parent | Cannot be more restrictive | public → public |
| Static / final | No | Cannot override |
Detailed Explanation & First Example
Let's start with a hands-on example. The program below shows the core idea behind Method Overriding in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.
class Animal
{
void sound() { System.out.println("Some sound"); }
}
class Dog extends Animal
{
@Override
void sound() { System.out.println("Bark"); }
}
class Main
{
public static void main(String args[])
{
Animal a = new Dog();
a.sound();
}
}
Examples — Beginner to Advanced
The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.
class Vehicle
{
void run() { System.out.println("Vehicle is running"); }
}
class Bike extends Vehicle
{
@Override
void run() { System.out.println("Bike is running fast"); }
}
class Main
{
public static void main(String args[])
{
new Bike().run();
}
}
class A
{
void hello() { System.out.println("Hello from A"); }
}
class B extends A
{
@Override
void hello()
{
super.hello();
System.out.println("Hello from B");
}
}
class Main
{
public static void main(String args[])
{
new B().hello();
}
}
Hello from B
class Shape { void draw() { System.out.println("Shape"); } }
class Circle extends Shape { @Override void draw() { System.out.println("Circle"); } }
class Square extends Shape { @Override void draw() { System.out.println("Square"); } }
class Main
{
public static void main(String args[])
{
Shape arr[] = { new Circle(), new Square(), new Shape() };
for (Shape s : arr) s.draw();
}
}
Square
Shape
class A
{
Number get() { return 10; }
}
class B extends A
{
@Override
Integer get() { return 20; } // covariant return
}
class Main
{
public static void main(String args[])
{
System.out.println(new B().get());
}
}
Notes & Tips
- Always use @Override — the compiler catches subtle mistakes.
- Final, private and static methods can't be overridden.
- Constructors can't be overridden — they aren't inherited.
- Override's access modifier must be at least as permissive as the parent.
- Runtime polymorphism enables dependency-inversion designs.
Real-World Use Cases
Strategy Pattern
Different algorithms share a base class and override a single method.
Game Entities
Player, Enemy and Boss override update() differently.
Frameworks
Spring, Android and JavaFX rely heavily on overridden lifecycle methods.
Custom toString()
Override toString() to print object data nicely.
Practice Questions
Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.
- Q1. Create a Shape class with subclasses Circle and Triangle that override
area(). - Q2. Override
toString()in a Book class. - Q3. Demonstrate calling the parent's overridden method via
super. - Q4. Create an Animal class and override
sound()in three subclasses. - Q5. Show why
finalmethods cannot be overridden.
Interview Questions
These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.
A subclass redefining an inherited method with the same signature to provide its own behaviour.
Overloading happens within a class with different parameters (compile-time). Overriding happens across parent-child classes with the same signature (runtime).
No — private methods are not inherited, so they can't be overridden.
Java's mechanism that decides which overridden method to call based on the actual object type at runtime.
No — constructors are not inherited.
FAQ
It tells the compiler your intent — typos and signature mismatches are caught at compile time.
No — static methods are hidden, not overridden.
No — only kept the same or made more permissive.
Returning a subtype of the parent's declared return type in an override.
Very slightly due to virtual dispatch, but modern JIT compilers usually optimize it away.
Common Mistakes to Avoid
Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Method Overriding in Java:
- Forgetting the semicolon
;at the end of statements while using Method Overriding. - Mixing up similar method names — read Java docs before using new APIs related to Method Overriding.
- Ignoring compiler warnings — they often hint at bugs that will appear later in production.
- Hard-coding values that should come from configuration files or environment variables.
- Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
- Skipping unit tests — small tests prevent big regressions, especially around control flow.
At-a-Glance
Best Practices
Follow Conventions
Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.
Write Tests
Cover happy path and edge cases with JUnit before shipping changes to production.
Keep Methods Short
A method should do one thing and fit on a single screen. Refactor when it grows.
Validate Inputs
Never trust user input. Validate at the boundary, fail fast and log meaningfully.
Comment the Why
Comments should explain why a decision was made — not what the code does line by line.
Refactor Often
Small frequent refactors are cheap and safe; big rewrites are risky and expensive.
Pro Tips
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| Method Overriding | Method Overriding concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
java.util, java.lang and java.io.
Summary
Method overriding is Java's mechanism for runtime polymorphism. A subclass provides its own implementation of a parent method, and Java picks the right one based on the actual object type. Always annotate overrides with @Override and use super to extend rather than replace the parent's behaviour.