Method Overloading in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community


In this programming language, multiple methods can be defined by the same name in a class. These methods can be defined with a different number of arguments and or different data types. This technique is known as method overloading.

 

For example, we define a class Calculator that will contain a method to calculate an average of integers. If we consider that a user passes two numbers or three numbers to the method to perform the operation, at this level of understanding we can't do it by defining a method. 

 

Moreover, we may need to pass a different number of arguments and or different data types to the method. Java provides a mechanism by which more than one function can be defined by the same name.

 

Thus, we can define the class as following and you can run the program to test.

Calculator.java
public class Calculator { public double average(int x, int y) { return (double) (x + y) / 2; } public double average(int x, int y, int z) { return (double) (x + y + z) / 3; } public double average(int x, double y) { return (x + y) / 2; } }

TestMain.java
public class TestMain { public static void main(String[] args) { Calculator cal = new Calculator(); System.out.println(cal.average(10, 2)); System.out.println(cal.average(10, 2, 7)); System.out.println(cal.average(10, 2.3)); } }



Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.