9️⃣

11.9 Overloading Methods

 
 
Overloading allows different methods to have the same name, but different method signatures. When you overload a method, the signature can differ by the number of input parameters or type of input parameters or both. Method overloading is mainly used to improve the code’s readability and usability. It is always easier to use one method name than having to use two if you want to perform the same action.
 
Analyze the code below.
public class Overloading { public static void main(String[] args) { // call 2-arg sum System.out.println(sum(2, 3)); // prints 5 // call 3-arg sum System.out.println(sum(1, 4, 7)); // prints 12 } public static int sum(int a, int b) { return a + b; } public static int sum(int a, int b, int c) { return sum(a, b) + c; } }
 
Notice that the overloaded methods (highlighted ones) have the same name. They even have the same return type. But they differ in their parameter lists. One method is used to sum 2 integers, while the other is used to sum 3 integers.
💡
Note: You may have noticed that the sum() method with 3 parameters actually utilizes the sum() method with 2 parameters. This method chaining is commonly used to avoid repeating code.
 
 

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.