Implementing Method Overloading and Method Overriding in Java
Course: Core Java Training
Topic: Implementing Method Overloading and Method Overriding
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Method Overloading and Method Overriding
Methods are an essential part of Java programming. They define the operations an object or class can perform and help developers organize reusable code. Java supports two important techniques for working with methods: method overloading and method overriding.
Both techniques allow methods with related purposes to share the same name, but they work differently. Method overloading allows multiple methods in the same class, or an inherited class context, to use the same name with different parameter lists. Method overriding allows a subclass to provide its own implementation of an eligible instance method inherited from a superclass.
These concepts support readable code, reusable functionality, and polymorphism. Understanding the differences between them is important for writing effective object-oriented Java programs.
Learning Objectives
- Understand the meaning and purpose of method overloading.
- Learn how to overload methods using different parameter lists.
- Understand method overriding and its relationship with inheritance.
- Implement both techniques through Java programs.
- Learn about compile-time and runtime polymorphism.
- Identify common errors and follow Java best practices.
2. What Is Method Overloading?
Method overloading is a Java feature that allows multiple methods to have the same name but different parameter lists. The methods can differ in the number of parameters, their data types, or their parameter order.
Overloaded methods commonly perform related operations while accepting different forms of input. For example, a calculator class might provide multiple add() methods to add two integers, three integers, or two decimal numbers.
The compiler determines which overloaded method to call by examining the method arguments and the available method signatures during compilation.
Key Characteristics of Method Overloading
- The methods have the same name.
- The parameter lists must differ in number, types, or order of types.
- Overloading can occur within a single class and can also involve inherited methods.
- It does not require inheritance.
- It is commonly associated with compile-time polymorphism.
- Changing only the return type does not create a valid overload.
3. Rules for Method Overloading
Java identifies methods using their names and parameter types. To overload a method, change its parameter list in a way that creates a distinct method signature.
3.1 Different Number of Parameters
class Display {
void show(int number) {
System.out.println("Number: " + number);
}
void show(int number, String text) {
System.out.println("Number: " + number);
System.out.println("Text: " + text);
}
}
The first method accepts one argument, while the second accepts two.
3.2 Different Parameter Types
class Printer {
void print(int value) {
System.out.println("Integer: " + value);
}
void print(String value) {
System.out.println("String: " + value);
}
}
Both methods are named print(), but one accepts an integer and the other accepts a string.
3.3 Different Parameter Order
class Information {
void display(String name, int age) {
System.out.println(name + " is " + age + " years old.");
}
void display(int age, String name) {
System.out.println(name + " is " + age + " years old.");
}
}
The parameter types appear in a different order, so the methods have different signatures.
3.4 Changing Only the Return Type Is Not Enough
// Invalid Java example
class Example {
int calculate(int value) {
return value * 2;
}
// Compilation error: same method signature
// double calculate(int value) {
// return value * 2.0;
// }
}
The two declarations have the same name and parameter list. A different return type alone does not make them valid overloads.
```html
4. Complete Example of Method Overloading
The following program demonstrates method overloading by defining multiple versions of an add() method. Each version accepts a different number or type of arguments.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.add(10, 20));
System.out.println(calculator.add(10, 20, 30));
System.out.println(calculator.add(5.5, 4.5));
}
}
Output:
30
60
10.0
Program Explanation
add(int a, int b) adds two integers.
add(int a, int b, int c) adds three integers.
add(double a, double b) adds two decimal values.
- All methods share the name
add(), but their parameter lists differ.
- The compiler selects the appropriate overload based on the arguments supplied to the method call.
5. Advantages of Method Overloading
- Improves readability: Related operations can share a meaningful method name.
- Supports flexible inputs: A method can handle different numbers or types of arguments.
- Reduces unnecessary method names: Developers do not need separate names such as
addTwoNumbers() and addThreeNumbers() for closely related operations.
- Supports compile-time polymorphism: The compiler resolves the applicable overloaded method during compilation.
- Simplifies API design: Libraries can provide convenient methods for different input formats.
6. What Is Method Overriding?
Method overriding occurs when a subclass provides a new implementation of an eligible instance method inherited from a superclass. The overriding method uses a compatible signature and return type, allowing the subclass to customize the inherited behavior.
Method overriding requires an inheritance relationship, such as a class extending another class or implementing an interface method. It is a major feature of runtime polymorphism because Java can select the implementation associated with the actual object's class when an overridden instance method is invoked.
Key Characteristics of Method Overriding
- The overriding method has the same name and compatible parameter types as the inherited method.
- The return type must be compatible. A covariant return type is allowed when the overriding method returns a subtype of the original return type.
- The overriding method cannot reduce the visibility of the inherited method.
- Private methods are not overridden because they are not inherited as accessible methods by subclasses.
- Static methods are hidden rather than overridden.
- The
@Override annotation helps the compiler verify the programmer's intention.
- Overriding an instance method enables runtime method dispatch.
7. Rules for Method Overriding
7.1 The Method Must Be Inherited and Eligible for Overriding
A subclass can override an eligible inherited instance method. For example, a Dog class can override an accessible makeSound() method declared in an Animal superclass.
7.2 The Method Signature Must Match
The method name and parameter types must match the inherited method's signature. If the parameter list changes, the subclass may be declaring an overloaded method instead of overriding the inherited one.
7.3 The Return Type Must Be Compatible
An overriding method can use the same return type or a permitted covariant reference return type. An incompatible return type results in a compilation error.
7.4 Visibility Cannot Be Reduced
An overriding method can have the same or wider accessibility, but it cannot reduce the access level of the inherited method. For example, a public method cannot be overridden with a protected or private method.
7.5 Use the @Override Annotation
The @Override annotation tells the compiler that a method is intended to override an inherited method. If the declaration does not actually override a suitable method, the compiler reports an error.
8. Complete Example of Method Overriding
This example demonstrates how a subclass can customize a method inherited from its superclass.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound.");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks.");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows.");
}
}
public class OverridingDemo {
public static void main(String[] args) {
Animal animal = new Animal();
Animal dog = new Dog();
Animal cat = new Cat();
animal.makeSound();
dog.makeSound();
cat.makeSound();
}
}
Output:
Animal makes a sound.
Dog barks.
Cat meows.
Program Explanation
Animal defines the original makeSound() method.
Dog overrides the method to print a dog-specific sound.
Cat overrides the same method to print a cat-specific sound.
- The variables
dog and cat are declared using the parent type, Animal, but refer to different subclass objects.
- At runtime, Java invokes the overridden method associated with the actual object's class.
9. Understanding Runtime Polymorphism
Runtime polymorphism occurs when an overridden instance method is selected according to the actual object at runtime. It allows code to work with a superclass or interface type while supporting different implementations.
Example
class Payment {
void processPayment() {
System.out.println("Processing a general payment.");
}
}
class CardPayment extends Payment {
@Override
void processPayment() {
System.out.println("Processing card payment.");
}
}
class UpiPayment extends Payment {
@Override
void processPayment() {
System.out.println("Processing UPI payment.");
}
}
public class PaymentDemo {
public static void main(String[] args) {
Payment payment;
payment = new CardPayment();
payment.processPayment();
payment = new UpiPayment();
payment.processPayment();
}
}
Output:
Processing card payment.
Processing UPI payment.
The variable payment has the type Payment, but it refers to different subclass objects. The actual object's class determines which overridden instance method is executed.
This approach is useful in payment systems, notification services, reporting tools, and other applications where multiple implementations follow a common interface.
10. Using the super Keyword with Method Overriding
The super keyword allows a subclass to invoke the superclass implementation of an overridden method. This is useful when the subclass wants to retain some of the original behavior while adding its own functionality.
Example
class Employee {
void displayRole() {
System.out.println("General employee.");
}
}
class Manager extends Employee {
@Override
void displayRole() {
super.displayRole();
System.out.println("Manages a team.");
}
}
public class SuperMethodDemo {
public static void main(String[] args) {
Manager manager = new Manager();
manager.displayRole();
}
}
Output:
General employee.
Manages a team.
The Manager class first invokes the superclass implementation through super.displayRole() and then executes its own additional statement.
11. Method Overloading vs. Method Overriding
Although the two concepts use methods with the same name, they differ in their requirements and behavior.
| Basis |
Method Overloading |
Method Overriding |
| Meaning |
Same method name with different parameter lists. |
A subclass provides a new implementation of an eligible inherited instance method. |
| Inheritance required |
No. |
Yes, through class inheritance or interface implementation. |
| Parameters |
Must differ in number, types, or order. |
Must match the inherited method's parameter types. |
| Return type |
May differ if the parameter lists distinguish the methods; return type alone cannot distinguish an overload. |
Must be the same or a permitted covariant reference type. |
| Polymorphism |
Commonly called compile-time polymorphism. |
Supports runtime polymorphism for instance methods. |
| Method selection |
The compiler resolves the applicable overload using argument types and method resolution rules. |
The implementation of the actual object's class is selected at runtime for an overridden instance method. |
| Annotation |
No special annotation is required. |
@Override is recommended. |
| Example |
add(int, int) and add(double, double). |
Dog.makeSound() overrides Animal.makeSound(). |
12. Compile-Time and Runtime Polymorphism
Polymorphism means that a common method name or type can support different operations or implementations. Method overloading and method overriding contribute to polymorphism in different ways.
Compile-Time Polymorphism
Method overloading is associated with compile-time polymorphism because the compiler determines which overload is applicable based on the method call's argument types and other method-resolution rules.
class Message {
void display(String text) {
System.out.println(text);
}
void display(int number) {
System.out.println(number);
}
}
Runtime Polymorphism
Method overriding is associated with runtime polymorphism because an overridden instance method is dispatched according to the actual object being used.
class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle.");
}
}
When draw() is called through a Shape reference that refers to a Circle object, Java executes the overridden implementation in Circle.
13. Can Static Methods Be Overloaded or Overridden?
Static methods belong to a class rather than to a particular instance. They can be overloaded when the parameter lists differ, but static methods are not overridden in the same way as instance methods.
Static Method Overloading
class Utility {
static void print(int number) {
System.out.println("Integer: " + number);
}
static void print(String text) {
System.out.println("Text: " + text);
}
}
public class StaticOverloadingDemo {
public static void main(String[] args) {
Utility.print(10);
Utility.print("Java");
}
}
Output:
Integer: 10
Text: Java
Static Method Hiding
class Parent {
static void show() {
System.out.println("Parent static method.");
}
}
class Child extends Parent {
static void show() {
System.out.println("Child static method.");
}
}
public class StaticMethodDemo {
public static void main(String[] args) {
Parent.show();
Child.show();
}
}
Output:
Parent static method.
Child static method.
This is called method hiding, not method overriding. The method invoked depends on the class through which the static method is called.
14. Practical Example: Notification Service
A notification service can use method overloading to support different input formats and method overriding to customize delivery behavior for different notification types.
class Notification {
void send(String message) {
System.out.println("Notification: " + message);
}
void send(String message, String recipient) {
System.out.println("To: " + recipient);
System.out.println("Notification: " + message);
}
}
class EmailNotification extends Notification {
@Override
void send(String message) {
System.out.println("Sending email: " + message);
}
}
class SmsNotification extends Notification {
@Override
void send(String message) {
System.out.println("Sending SMS: " + message);
}
}
public class NotificationDemo {
public static void main(String[] args) {
Notification notification = new Notification();
notification.send("Welcome!");
notification.send("Your account is ready.", "[email protected]");
Notification email = new EmailNotification();
Notification sms = new SmsNotification();
email.send("Your report is ready.");
sms.send("Your verification code is 1234.");
}
}
Output:
Notification: Welcome!
To: [email protected]
Notification: Your account is ready.
Sending email: Your report is ready.
Sending SMS: Your verification code is 1234.
What This Example Demonstrates
- The
Notification class overloads send() to accept different parameter lists.
EmailNotification and SmsNotification override the one-argument send() method.
- The overloaded two-argument method remains available through the inherited API unless it is otherwise hidden or overridden with the same signature.
- The example combines compile-time method selection with runtime method dispatch.
15. Common Errors and How to Fix Them
| Error or Mistake |
Cause |
Solution |
| Overloading methods by return type only |
The parameter lists are identical, so the declarations conflict. |
Change the parameter list or use a distinct method name. |
| Incorrect method signature while overriding |
The subclass method has different parameter types or a different name. |
Match the inherited method signature and use @Override. |
| Reducing method visibility |
The overriding method is less accessible than the inherited method. |
Keep the same or wider access level. |
| Overriding a final method |
Methods declared final cannot be overridden. |
Use the inherited method or redesign the superclass if appropriate. |
| Trying to override a static method |
Static methods are hidden, not overridden. |
Use instance methods when runtime polymorphism is required. |
| Unexpected overloaded method selection |
The compiler uses the argument types and method-resolution rules, not just the runtime class of an argument. |
Review the declared types, available overloads, and possible conversions. |
| Ambiguous overloaded call |
More than one overload may be applicable without a single most-specific choice. |
Use clearer parameter types or explicitly cast arguments where appropriate. |
16. Best Practices
- Use overloading when methods perform closely related tasks but require different input parameters.
- Keep overloaded methods easy to distinguish and avoid unnecessarily complicated overload combinations.
- Use overriding when a subclass genuinely needs to specialize inherited behavior.
- Add
@Override to overridden methods to catch signature mistakes.
- Follow the superclass method's behavioral contract when overriding it.
- Do not reduce the accessibility of an overridden method.
- Use
super.methodName() when the parent implementation should be preserved as part of the subclass behavior.
- Avoid using inheritance solely to reuse a few unrelated methods; consider composition instead.
- Write unit tests for overloaded methods with different argument combinations and for overridden methods in each subclass.
17. Practical Exercises
- Calculator: Create overloaded
multiply() methods for two integers, three integers, and two double values.
- Area calculator: Create overloaded
calculateArea() methods for a square and rectangle using different parameter lists.
- Employee hierarchy: Create an
Employee class with a displayDetails() method. Override it in Manager and Developer.
- Animal sounds: Create an
Animal class and override makeSound() in Dog, Cat, and Cow.
- Notification service: Overload a method to accept a message alone or a message and recipient. Override message delivery behavior in email and SMS subclasses.
- Method selection: Create overloaded methods that accept
int, double, and String arguments. Predict the selected method for several calls and then verify the results.
18. Mini Project: Shape Calculator
Objective: Build a small Java program that uses method overloading and method overriding to calculate or display shape information.
Requirements
- Create a superclass named
Shape with a display() method.
- Create subclasses named
Circle and Rectangle.
- Override
display() in each subclass to print shape-specific details.
- Create a utility class with overloaded
calculateArea() methods that accept appropriate parameters for a circle and a rectangle.
- Use a superclass reference to demonstrate runtime polymorphism.
- Test the program with different dimensions and verify the calculated areas.
Expected Learning Outcomes
After completing this project, learners should be able to distinguish method overloading from overriding, select suitable method signatures, apply inheritance, and understand how Java chooses overloaded and overridden methods.
19. Core Java Interview Questions and Answers
Q1. What is method overloading in Java?
Answer: Method overloading allows multiple methods to share the same name while having different parameter lists. It is commonly associated with compile-time polymorphism.
Q2. What is method overriding in Java?
Answer: Method overriding occurs when a subclass provides a compatible implementation of an eligible inherited instance method. It supports runtime polymorphism.
Q3. Can methods be overloaded by changing only their return types?
Answer: No. The parameter lists must distinguish overloaded methods. Changing only the return type is not sufficient.
Q4. Is inheritance required for method overloading?
Answer: No. Methods can be overloaded within a single class. Inheritance may also be involved in an overloaded method set.
Q5. Is inheritance required for method overriding?
Answer: Yes. Overriding involves providing an implementation for an eligible inherited instance method, including methods inherited through an interface.
Q6. What is the purpose of the @Override annotation?
Answer: It indicates that a method is intended to override an inherited method and allows the compiler to detect mistakes in the declaration.
Q7. Can a static method be overridden?
Answer: No. A static method with the same signature in a subclass hides the superclass method instead of overriding it.
Q8. Can a private method be overridden?
Answer: No. A private method is not inherited as an accessible method by a subclass. A same-named method declared in the subclass is a separate method.
Q9. What is runtime polymorphism?
Answer: Runtime polymorphism occurs when Java selects an overridden instance method according to the actual object's class at runtime.
Q10. What is the difference between overloading and overriding?
Answer: Overloading uses the same method name with different parameter lists and is resolved at compile time. Overriding provides a subclass-specific implementation of an inherited instance method and uses runtime method dispatch.
Q11. Can an overriding method have a different return type?
Answer: It can use the same return type or a permitted covariant reference return type. An incompatible return type is not allowed.
Q12. Can an overriding method reduce visibility?
Answer: No. An overriding method must have the same or wider accessibility than the overridden method.
Q13. Can constructors be overridden?
Answer: No. Constructors are not inherited, so they cannot be overridden. Constructors can be overloaded using different parameter lists.
Q14. Can a subclass overload a method inherited from its parent?
Answer: Yes. A subclass can declare another method with the same name but a different parameter list, provided the declarations are valid.
Q15. What does the super keyword do in method overriding?
Answer: It allows a subclass to call the superclass implementation of an overridden method.
20. Quick Revision Notes
- Method overloading means the same method name with different parameter lists.
- Method overriding means providing a new implementation of an eligible inherited instance method.
- Overloading does not require inheritance.
- Overriding requires an inheritance or interface implementation relationship.
- Return type alone cannot distinguish overloaded methods.
- An overriding method must have a compatible return type and cannot reduce visibility.
- The
@Override annotation is recommended for overriding methods.
- Overloading is commonly associated with compile-time polymorphism.
- Overriding supports runtime polymorphism.
- Static methods can be overloaded, but same-signature static methods in a subclass hide rather than override.
- Constructors can be overloaded but cannot be overridden.
- The
super keyword can call the superclass implementation of an overridden method.
21. Conclusion
Method overloading and method overriding are essential concepts in Java's object-oriented programming model. Overloading makes methods more flexible by allowing related operations to use the same name with different parameter lists. Overriding allows subclasses to customize inherited behavior and is fundamental to runtime polymorphism.
To master these concepts, practice writing overloaded calculator methods, overriding methods in class hierarchies, and using superclass references to work with different subclass objects. Understanding method signatures, access rules, return types, and the role of @Override will help you write clearer and more reliable Java programs.
Continue Learning with JustAcademy
Explore the Core Java Training Course to continue learning Java methods, classes, objects, inheritance, polymorphism, and other object-oriented programming concepts.
Register for a Course Demo to learn more about the training, or visit the JustAcademy website.