Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Method Overloading in Java
3.
Example of Method Overloading:
4.
Method Overriding in Java
5.
Example of Method Overriding:
6.
Difference Between Method Overloading and Method Overriding
7.
Frequently Asked Questions
7.1.
Can a method be both overloaded and overridden?
7.2.
Does method overloading affect method execution speed?
7.3.
Is it possible to override a private method?
8.
Conclusion
Last Updated: Apr 27, 2024
Easy

Method Overloading and Method Overriding

Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In Java, methods are a key part of object-oriented programming. They allow us to define the behavior of objects & organize code into reusable parts. Two important concepts related to methods are method overloading & method overriding. Method overloading lets us define multiple methods with the same name but different parameters, while method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Understanding these concepts is essential for writing flexible, maintainable Java code. 

Method Overloading and Method Overriding

In this article, we'll learn the details of method overloading & overriding, see examples of each, & learn how they differ.

Method Overloading in Java

Method overloading is a technique where multiple methods in a class have the same name but different parameters. This feature allows programmers to create several methods that perform similar tasks but with different types or numbers of inputs. It's a key aspect of Java that helps in making the code cleaner & more intuitive.

Here are the key points to remember about method overloading:

  • Methods must have the same name.
     
  • Methods must have different parameter lists.
     
  • Return types can be different.
     
  • Overloading is resolved at compile-time.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of Method Overloading:

To see method overloading in action, let's consider a simple class that can calculate the area of different shapes. We might overload the area method to handle different shapes like circles & rectangles by using different sets of parameters.

public class Shape {
    // Method to calculate the area of a circle
    public double area(double radius) {
        return Math.PI * radius * radius;
    }

  // Method to calculate the area of a rectangle
    public double area(double length, double width) {
        return length * width;
    }
}


In this example, the Shape class has two area methods. One calculates the area of a circle when given the radius & the other calculates the area of a rectangle when provided with length & width. This is method overloading: the same method name with different parameters to perform closely related actions.

Method Overriding in Java

Method overriding is another important concept in Java that allows a subclass to provide a specific implementation of a method that is already provided by one of its parent classes. This is used to give specific behaviors to inherited methods without changing the method's name or its original purpose in the parent class.

Here are the key points to remember about method overriding:

  • Methods must have the same name & signature (parameter list).
     
  • The return type of the overriding method must be the same or a subtype of the return type of the overridden method.
     
  • The access modifier of the overriding method cannot be more restrictive than the overridden method.
     
  • Overriding is resolved at runtime (dynamic binding).

Example of Method Overriding:

Consider a class Animal that has a method called sound(). Different animals make different sounds, so in subclasses, we can override this method to reflect their unique sounds.

class Animal {
    // Method in the base class
    public void sound() {
        System.out.println("This animal makes a sound");
    }
}
class Dog extends Animal {
    // Overriding method in the subclass
    @Override
    public void sound() {
        System.out.println("Dog barks");
    }
}
class Cat extends Animal {
    // Overriding method in the subclass
    @Override
    public void sound() {
        System.out.println("Cat meows");
    }
  }


In this example, the Dog & Cat classes override the sound() method of the Animal class to provide specific implementations for each animal type. The @Override annotation is used to make it clear that the method is meant to replace one in the parent class.

Method overriding is essential for achieving runtime polymorphism & can be particularly useful in cases where the behavior inherited from the parent class needs to be modified rather than completely replaced.

Difference Between Method Overloading and Method Overriding

FeatureMethod OverloadingMethod Overriding
DefinitionMultiple methods have the same name but different parameters (type, number) in the same class.A subclass provides a specific implementation for a method that is already defined in its superclass.
PurposeTo perform a single operation in different ways, enhancing program readability.To modify or extend the behavior of an inherited method.
Parameter ListMust differ in type, number, or both.Must be the same as the method in the superclass.
Return TypeCan vary but is not solely sufficient for overloading.Must be the same as the method in the superclass or covariant (subclass types).
Usage ContextUsed within the same class.Used across a class hierarchy (superclass and subclasses).
Access ModifiersCan be different from the original method.Cannot be more restrictive than the original method.
Scope of ImpactLocal to the class where it is defined.Global to all classes that inherit or interact with the superclass.

Frequently Asked Questions

Can a method be both overloaded and overridden?

Yes, a method can be both overloaded in its class and overridden in a subclass, as these are independent concepts in Java.

Does method overloading affect method execution speed?

No, method overloading does not impact execution speed as it is resolved at compile time, making it just as fast as calling any other method.

Is it possible to override a private method?

No, private methods are not visible outside their class, so they cannot be overridden; they can only be accessed within the class they are declared in.

Conclusion

In this article, we have learned about two powerful concepts in Java: method overloading and method overriding. We learned how method overloading allows multiple methods to share the same name but with different parameters, enhancing code readability and usability. We also discussed method overriding, where a subclass provides specific implementations of a method defined in its superclass, allowing for dynamic method dispatch and polymorphic behaviors. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Constructor Chaining In Java
Next article
Private Constructors and Singleton Classes in Java
Live masterclass