Method overriding in Java

 

✅ What is Method Overriding in Java?

Method overriding in Java occurs when a subclass provides a specific implementation of a method that is already defined in its superclass.

The overridden method in the subclass should have:

  • Same method name

  • Same return type (or subtype - called covariant return type)

  • Same parameter list


๐Ÿง  Purpose of Overriding

To implement runtime polymorphism, where the method that gets called depends on the object's runtime type, not the reference type.


๐Ÿ“˜ Example of Method Overriding

class Animal {
void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { // Overriding the sound() method @Override void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); // Upcasting a.sound(); // Calls Dog's overridden method } }

๐Ÿงพ Output:

Dog barks

๐Ÿ”Ž Key Points about Method Overriding

Rule / FeatureDescription
Same SignatureName and parameters must be identical
Access ModifierCan’t be more restrictive than the superclass method
Return TypeMust be the same or a subtype (covariant)
@Override AnnotationOptional but recommended – helps catch errors
Static/Private/Final MethodsCannot be overridden
ConstructorsCannot be overridden

๐Ÿ” Access Modifier Example

class Parent {
protected void show() { System.out.println("Parent class"); } } class Child extends Parent { // Must be same or more visible (protected or public) @Override public void show() { System.out.println("Child class"); } }

❌ Invalid Overriding Example (Compile-time Error)

class Parent {
private void show() { System.out.println("Parent"); } } class Child extends Parent { @Override void show() { // ❌ Cannot override private method System.out.println("Child"); } }

Explanation: show() in Parent is private – not visible to Child.


๐Ÿ†š Method Overloading vs Method Overriding

FeatureMethod OverloadingMethod Overriding
Occurs inSame classBetween superclass and subclass
ParametersMust differMust be the same
Return TypeCan differMust be same or subtype
Access ModifierAnyCannot be more restrictive
Polymorphism TypeCompile-timeRuntime

๐Ÿงช Real-world Analogy

Think of a base class Printer that prints documents. A ColorPrinter (subclass) can override the method to print in color, while BlackAndWhitePrinter prints in black-and-white – same method, different behavior.

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Java Compiler and Java Virtual Machine