Method Overriding in Java Tutorial
Chapter 13 · Java Programming Series
PBA Institute 11 min read Intermediate 2024

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

RuleRequiredNoteExample
Same nameYesIdentical nameshow()
Same paramsYesType & order match(int, String)
Return typeSame/CovariantCan be subclass of originalNumber → Integer
Access≥ parentCannot be more restrictivepublic → public
Static / finalNoCannot 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.

Override show() Method
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();
    }
}
Output Bark

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.

Vehicle Example
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();
    }
}
Output Bike is running fast
Using super to Call Parent
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();
    }
}
Output Hello from A
Hello from B
Polymorphic List
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();
    }
}
Output Circle
Square
Shape
Covariant Return Type
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());
    }
}
Output 20

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 final methods 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.

Q1 What is method overriding?
A subclass redefining an inherited method with the same signature to provide its own behaviour.
Q2 Difference between overloading and overriding?
Overloading happens within a class with different parameters (compile-time). Overriding happens across parent-child classes with the same signature (runtime).
Q3 Can private methods be overridden?
No — private methods are not inherited, so they can't be overridden.
Q4 What is dynamic method dispatch?
Java's mechanism that decides which overridden method to call based on the actual object type at runtime.
Q5 Can constructors be overridden?
No — constructors are not inherited.

FAQ

FAQ 1 Why is @Override important?
It tells the compiler your intent — typos and signature mismatches are caught at compile time.
FAQ 2 Can I override a static method?
No — static methods are hidden, not overridden.
FAQ 3 Can the access modifier be reduced when overriding?
No — only kept the same or made more permissive.
FAQ 4 What is covariant return type?
Returning a subtype of the parent's declared return type in an override.
FAQ 5 Does overriding affect performance?
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

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
Function Overloading Date Time Functions OOP Best Practices

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

TIP 01 Use clear, descriptive identifiers when writing code involving Method Overriding — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
Method OverridingMethod Overriding conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV Function Overloading — strengthens your understanding of the previous building block.
NEXT Date Time Functions — the natural progression after mastering Method Overriding.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore 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.

Continue Learning