Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Overloading Methods
AP® Computer Science A (Java) Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source AP® (Advanced Placement®) Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency. It is a substantial amount of coursework that represents a typical year of high school-level study or a semester of a University computer science course. This course may also be used to prepare for the AP® Computer Science A exam.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
In Java, the concept of "overloading" is when two or more methods of a class have the same name but different "parameter lists". In this special case, when a method is called, the program calls the correct method by checking the parameters. To understand this concept further, let's think back to when we were working with the Math class. When we used the method Math.abs(), we experienced the concept of overloading as the method had four different choices for the parameter; the data types int, double, float, and long. Let's dive into how we can overload a method.
OverloadingMethodsExample.java
package exlcode;
public class OverloadingMethodsExample {
public static float exampleVariableOne = 3.14f;
public static double exampleVariableTwo = Math.PI;
public static void main(String[] args) {
print(exampleVariableOne);
print(exampleVariableTwo);
}
// two identical methods with different parameters
// takes in float value as a parameter
public static void print(float parameterOne) {
System.out.println("float: " + parameterOne);
}
// takes in a double value as a parameter
public static void print(double parameterOne) {
System.out.println("double: " + parameterOne);
}
}
The method named print() is overloaded when we create two methods with the same name containing different parameters. One takes in double values while the other takes float values. The only difference between the methods has to be the parameters in order for it to be considered "overloading". One rule to keep in mind when working with overloaded methods is that return types for the methods cannot be the only thing that separates one method from the other. For example, creating two methods with the headers public int methodA() and public double methodA() will result in an error.