Java Method Overloading and Conditions.

What is Java Method Overloading

Java method Overloading is a feature where two methods in a class can have the same name provided they have different parameter lists. So if you have a class called ClassA, it can have two methods both named methodA, however, the two methods should take in different parameters. for example, If the first takes in an int, the second should take in a String or two integers etc. We will look at some scenarios that qualify for method overloading and others that don’t. Here’s an example:

Java Method Overloading and parameters

We look at some examples for method overloading by changing the method parameters:

  1. Different parameter types: If you have two methods that have the same number of parameters but different types then the overloading works. Look at Method 4 and Method 6.
  2. Parameter Order: If the two methods have the same number of parameters and the same type of parameters but if the order of parameters is different, overloading works. Look at method 11 and Method 12.
  3. Derived Parameter types : If the two methods differ in parameter type, however, if one parameter is a subclass of the other parameter, method overloading still works. Look at Method 7 and Method 8
  4. Varargs : You can use a method with varargs to overload with a method that takes multiple parameters of same type. Look at method 9 and Method 10. Method 9 uses two parameters country and state whereas method 10 uses a … to take in multiple parameters. However, if you call a method with two String parameters the JVM would call method 9 and not method 10.
  5. Java Method Overloading and Exception

    If a class has two methods with the same name and parameters but differ in the Exceptions thrown then the compiler would throw and error since this does not qualify as method overloading. Look at method 1 and Method 3.

    Java Method Overloading and Return Type

    Method overloading does not work if the method name and parameters are same but the return type is different. Look at Method 1 and Method 2.

    Java Method Overloading and static

    Making one method static when two methods have same name and arguments does not qualify as overloading. Look at Method 4 and Method 5.

    Diagram for valid Java method overloading conditions

    Java Method Overloading

    This completes our discussion on method overloading. In the next tutorial, we will look at Method overriding.

    Java Method Overloading and Conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top