From 46b10c2f657067b287dd92f87225685334aa07cc Mon Sep 17 00:00:00 2001 From: jamiesteck Date: Fri, 15 Mar 2019 00:41:52 -0700 Subject: [PATCH] added method overloading (#28813) * added method overloading added a section describing method overloading * Update index.md --- guide/english/java/methods/index.md | 32 ++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/guide/english/java/methods/index.md b/guide/english/java/methods/index.md index 5d38d72bfc..15cd24a277 100644 --- a/guide/english/java/methods/index.md +++ b/guide/english/java/methods/index.md @@ -106,5 +106,35 @@ public class Car { ``` The `Car` class and the `Car(String model, int numberOfWheels)` method have to have the same name in order for java to know that it is the constructor. Now anytime you instantiate a new `Car` instance with the `new` keyword you will need to call this constructor and pass in the needed data. - When we don't specifically define a constructor for a class, java creates a default constructor. This is a non-parameterized constructor, so it does not contain or accept any arguments. The default constructor calls the super class constructor and initializes all necessary instance variables + +## Method Overloading + +Method overloading occurs when two methods have the same name, but different parameters, different parameter orders or different types. For example, the code below shows three different methods titled "max". This is allowed because the methods have either a different number of parameters (two vs three) or different type of parameters (int vs double.) + +``` +public static int max(int num1, int num2){ + if(num1 > num2) + return num1; + else + return num2; +} + +public static int max(int num1, int num2, int num3){ + return max(max(num1, num2), num3); +} + +public static double max(double num1, double num2){ + if(num1 > num2) + return num1; + else + return num2; +} +``` +The correct method is executed based on the number of arguments passed to the method. + +Method overloading is used frequently in the [Math class](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html) + +## More information: + +* [Oracle](https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html)