21
FebMethod Overloading And Overriding In Java (With example)
Method Overloading Vs. Overriding In Java
Method overloading and overriding in Javais essential for writing flexible and efficient code in Java programming. Overloading in Java allows you to create multiple methods with the same name but different parameters, while Overriding in Java lets you change the behavior of a method from a parent class. Both concepts are key aspects of polymorphism, and we’ll explore their differences and how to use them effectively in your coding projects!
In this Java tutorial, we will explore more aboutOverloading and Overriding in Java, including What is Method Overriding in Java?, What is Method Overloading in Java?, Differences Between Overloading and Overriding in Java, and a lot more.
What is Method Overriding in Java?
Method overriding in Java is like giving a personal touch to a method from the parent class. It happens when a child class provides its own version of a method that’s already defined in the parent class. This allows the child class to change or extend the behavior of the inherited method, making it work in a way that’s unique to the child.
Key Characteristics of Method Overriding in Java
- Inheritance Requirement: A superclass-subclass relationship is necessary for overriding.
- Same Method Signature: The name, parameters, and return type of overriding methods are all the same.
- Runtime Polymorphism: The object type determines at runtime which method should be used.
Advantages of Method Overriding
- Method overriding lets you change how a parent class method works in a child class, making the code more flexible.
- It helps with code reuse, as the child class can use the existing method structure and just improve or modify it.
- It supports runtime polymorphism, meaning the right method is chosen while the program is running based on the object type.
- It makes the code easier to extend since you can add new behavior without changing the original code.
- Overriding helps in improving or customizing inherited behavior for specific needs in your child's classes.
Disadvantages of Method Overriding
- Method overriding can make the code harder to follow, especially when multiple classes in Java override the same method in different ways.
- If you override a method incorrectly, it can lead to unexpected behavior and bugs in the program.
- It can sometimes make the code more complex, especially if you have a deep inheritance chain, as changes in one class can affect many others.
- Overriding requires the child class to use the exact method signature as the parent class, which can be restrictive.
- You may lose the original behavior of the parent class method, which can be a problem if you need to use it later.
Examples of Method Overriding
// Superclass
class Company {
void NoofEmployees() {
System.out.println("Number of Employees");
}
}
// Subclass overriding method
class Employee extends Company {
@Override
void NoofEmployees() {
System.out.println("There are 50 employees");
}
}
// Main class to demonstrate method overriding
public class Main {
public static void main(String[] args) {
Company comp = new Company(); // Create Company object
comp.NoofEmployees(); // Output: NumberofEmployees
Company emp = new Employee(); // Company reference but Dog object
emp.NoofEmployees(); // Output: There are 50 employees
}
}
Output
NumberofEmployees
There are 50 employees
Explanation
- Company Class: This is the superclass with a method NoofEmployees() that prints "Number of Employees".
- Employee Class: Extends Company and overrides the NoofEmployees() method to print " There are 50 employees" instead.
- Main Class: In the main method, A Company object ( comp) calls NoofEmployees(), which prints "Number of Employees".
- An Employee object is assigned a reference of type Company ( employee). When employee. NoofEmployees() is called, it dynamically binds to the NoofEmployees() method in the Employee class due to method overriding, printing " There are 50 employees."
Usage
- Used in inheritance to implement certain behaviors in subclasses.
- It offers specific implementations of the methods used by abstract classes or interfaces.
Advantages of Method Overriding
- Method overloading makes your code easier to read by using the same name for similar tasks.
- You don’t have to create different method names, which keeps your code shorter and simpler.
- It lets you handle different types or numbers of inputs with just one method name.
- The program decides which method to use before running, making the code faster.
- Reusing the same method name helps avoid repetition, making your code cleaner and easier to maintain.
Disadvantages of Method Overriding
- Overloading can get confusing if there are too many methods with similar parameters. You might struggle to know which one to use.
- It can be tricky to maintain because, when you make changes, you have to check all the overloaded methods to ensure they’re still working properly.
- Having many overloaded methods can make your code look more complex, which might be hard to understand, especially for someone new to the code.
- Overloading helps with parameters, but it can't change behavior just by the return type, so you have less flexibility.
What is Method Overloading in Java?
Method overloading in Java is like giving multiple ways to perform a task using the same name. It happens when a class has two or more methods with the same name but different parameter lists (like a different number or type of argument). This allows the method to adapt and handle various inputs while keeping the code clean and readable.
Key Characteristics of Method Overloading in Java
- Same Method Name: The names of the overloading methods are the same.
- Different Parameters: Parameters might be different in terms of their type, number, or both.
- Compile Time Resolution: The method signature is used to determine how overloading is resolved at build time.
Advantages of Method Overloading
- Method overloading makes your code easier to read by using the same name for similar tasks.
- You don’t have to create different method names, which keeps your code shorter and simpler.
- It lets you handle different types or numbers of inputs with just one method name.
- The program decides which method to use before running, making the code faster.
- Reusing the same method name helps avoid repetition, making your code cleaner and easier to maintain.
Disadvantages of Method Overloading
- Overloading can get confusing if there are too many methods with similar parameters. You might struggle to know which one to use.
- It can be tricky to maintain because, when you make changes, you have to check all the overloaded methods to ensure they’re still working properly.
- Having many overloaded methods can make your code look more complex, which might be hard to understand, especially for someone new to the code.
- Overloading helps with parameters, but it can't change behavior just by the return type, so you have less flexibility.
Examples of Method Overloading
public class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}
// Method to add three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Method to add two doubles
public double add(double a, double b) {
return a + b;
}
// Method to concatenate two strings
public String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
// Calling different overloaded methods
int sum1 = calc.add(5, 10);
int sum2 = calc.add(5, 10, 15);
double sum3 = calc.add(2.5, 3.5);
String concatenatedString = calc.add("Hello, ", "World!");
// Displaying results
System.out.println("Sum of integers (5 + 10): " + sum1);
System.out.println("Sum of integers (5 + 10 + 15): " + sum2);
System.out.println("Sum of doubles (2.5 + 3.5): " + sum3);
System.out.println("Concatenated string: " + concatenatedString);
}
}
Output
Sum of integers (5 + 10): 15
Sum of integers (5 + 10 + 15): 30
Sum of doubles (2.5 + 3.5): 6.0
Concatenated string: Hello, World!
Explanation
- The Calculator class has multiple add() methods that perform different tasks, like adding integers, doubles, or concatenating strings.
- The methods are overloaded, meaning they have the same name but different numbers or types of parameters.
- In the main() method, these methods are called with appropriate inputs, and the results are displayed, like sums of numbers or a concatenated string.
- It provides several methods (such as add(int, int) and add(double, double)) for calling a method with various parameter types.
- It is used to define constructors for object initialization that take distinct argument lists.
Differences Between Overloading and Overriding in Java
In the above, we have information aboutmethod overloading and overriding in Java. Now it's time to differentiate both of them thoroughly, which will help you all understand this clearly.
Factor | Method Overloading | Method Overriding |
Definition | Having multiple methods with the same name but different parameters in the same class. | Providing a new implementation for a method already defined in the parent class. |
Purpose | To perform similar tasks in different ways (based on input types/parameters). | To change or extend the behavior of an inherited method. |
Class Involvement | Happens within the same class. | Involves a parent class and a child class. |
Method Signature | Methods must have different parameter lists (number or type of arguments). | The method signature must be the same as the parent method. |
Return Type | It can have different return types (as long as parameters differ). | It must have the same return type (or a covariant return type). |
Polymorphism Type | Compile-time polymorphism. | Run-time polymorphism. |
Annotations Used | No annotations are needed. | Uses @Override annotation (optional but recommended). |
Conclusion
In conclusion, overloading and overriding in Java are important ideas that make coding more powerful and flexible. Overloading in Java lets you create methods with the same name but different inputs while overriding in Java allows a child class to change the behavior of a method from its parent class. Learning these concepts helps you write better programs and makes your code easier to use and understand.
Master tech skills for free with our Free Tech Courses—perfect for beginners and experts alike!Advance your career with our Azure AI & ML Certification Training and Azure Cloud DevOps Engineer Certification Training, designed to make you job-ready.
Mostly Asked Articles: |
Java vs Python: Which Language is Better for the Future? |
Lambda Expressions in Java: Explained in Easy Steps |
HashMap in Java: A Detailed Explanation |
Q 1: Which of the following is true about method overloading in Java?
Explanation: Method overloading in Java allows multiple methods with the same name in a class, provided they differ in the number or type of their parameters.
Q 2: What is the key difference between method overloading and method overriding?
Explanation: Method overloading is a compile-time concept, while method overriding is a runtime concept because the method call is resolved using dynamic dispatch.
Q 3: Which rule must be followed in method overriding but not in method overloading?
Explanation: Method overriding requires the same method signature (name, parameter list, and return type) as the method in the parent class, which is not a requirement for overloading.
Q 4: Which of the following is true about method overriding in Java?
Explanation: Method overriding enables a subclass to provide a specific implementation of a method that is already defined in its parent class, following the same signature.
Q 5: Which of the following can be overloaded in Java?
Mostly Asked Questions on Interviews |
Top 50 Java MCQ Questions |
Top 50+ Java 8 Interview Questions & Answers 2025 |
Java Full Stack Developer Interview Questions |