DEV Community

Kanishka Shrivastava
Kanishka Shrivastava

Posted on

#java #oop #polymorphism #programming

Java Concepts I’m Mastering – Part 6: Method Overriding & Runtime Polymorphism

Continuing my journey of mastering Java fundamentals.

Today’s concept: Method Overriding — the foundation of runtime polymorphism.

What is Method Overriding?

Method Overriding happens when:

A child class provides its own implementation

Of a method already defined in the parent class

Same method name.
Same parameters.
Different behavior.

Example

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}
Enter fullscreen mode Exit fullscreen mode

Now:

Animal a = new Dog();
a.sound();
Enter fullscreen mode Exit fullscreen mode

Output:

Dog barks
Enter fullscreen mode Exit fullscreen mode

Even though the reference type is Animal,
the method of Dog is called.

This is Runtime Polymorphism.

Why is it Powerful?

Enables dynamic behavior

Supports clean extensible design

Core concept behind frameworks & APIs

Important Rules

Method name must be same

Parameters must be same

Access level cannot be more restrictive

Use @override for safety

What I Learned

Overloading = Compile-time

Overriding = Runtime

Polymorphism makes Java flexible and scalable

This concept changed how I see object-oriented design.

Next in the series: Abstraction in Java (Abstract Classes vs Interfaces)

Top comments (0)