Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
Method overloading in Java is the ability to define multiple methods with the same name within the same class, but with different parameter lists. The Java compiler is able to differentiate between overloaded methods based on the number and types of arguments passed to the method. This tutorial will cover the basics of method overloading in Java, including some examples and best practices.
You can overload a method by creating multiple methods with the same name, but with different parameter types.
public class Calculator { public int add(int a, int b) { return a + b; } public double add(double a, double b) { return a + b; } }
In this example, there are two add()
methods with different parameter types: one accepts two int
parameters, and the other accepts two double
parameters.
You can also overload a method by creating multiple methods with the same name, but with a different number of parameters.
public class Calculator { public int add(int a, int b) { return a + b; } public int add(int a, int b, int c) { return a + b + c; } }
In this example, there are two add()
methods with a different number of parameters: one accepts two int
parameters, and the other accepts three int
parameters.
When calling an overloaded method, the Java compiler will automatically select the appropriate method based on the number and types of arguments.
public class Main { public static void main(String[] args) { Calculator calculator = new Calculator(); int intResult = calculator.add(1, 2); double doubleResult = calculator.add(1.0, 2.0); System.out.println("intResult: " + intResult); // Output: intResult: 3 System.out.println("doubleResult: " + doubleResult); // Output: doubleResult: 3.0 } }
int
to double
), as this may cause unexpected results or ambiguous method calls.This tutorial introduced the basics of method overloading in Java, including creating overloaded methods with different parameter types and numbers, and some best practices to follow. Method overloading is a powerful feature in Java that allows you to create more flexible and expressive APIs while keeping your code clean and organized.
Java method overloading with different parameter types:
void printInfo(String message) {...} void printInfo(int number) {...}
Java method overloading with inheritance:
class SuperClass { void display(int num) {...} } class SubClass extends SuperClass { void display(String message) {...} }
Java method overloading and varargs:
void processNumbers(int... numbers) {...}