Understanding Method Overriding in Java

java dev.to

One of the key features of Object-Oriented Programming (OOP) in Java is Method Overriding. It allows a subclass to provide its own implementation of a method that is already defined in its parent class. This helps achieve runtime polymorphism, making Java programs more flexible and reusable.

In this blog, we'll learn what method overriding is with a simple example.

What is Method Overriding?

Method Overriding is a feature in Java where a child class provides a specific implementation of a method that is already present in the parent class.

To override a method:

  • The parent and child class methods must have the same method name.
  • They must have the same parameters.
  • They must have the same return type (or a compatible one).

Example

class Animal {

void sound() {
    System.out.println("Animals make sounds.");
}
Enter fullscreen mode Exit fullscreen mode

}

class Dog extends Animal {

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

}

public class Main {

public static void main(String[] args) {

    Dog d = new Dog();

    d.sound();

}
Enter fullscreen mode Exit fullscreen mode

}

Output

Dog barks.

Explanation

  • The "Animal" class contains a method called "sound()".
  • The "Dog" class extends "Animal" and overrides the "sound()" method.
  • When the "sound()" method is called using the "Dog" object, Java executes the overridden method in the child class.

Advantages of Method Overriding

  • Achieves Runtime Polymorphism.
  • Improves code flexibility.
  • Allows subclasses to customize inherited methods.
  • Promotes code reusability.

Conclusion

Method overriding is an important Java concept that allows a child class to redefine the behavior of a method inherited from its parent class. It plays a major role in achieving runtime polymorphism and makes applications more flexible and maintainable.

Method Overriding means redefining an inherited method in a child class using the same method signature to provide a different implementation.

Source: dev.to

arrow_back Back to Tutorials