Method Overloading


Method Overloading

This is a concept where we can declare multiple methods with same name but different parameters in the same class. Method overloading is supported by java and always occurs in the same class. This is one of the ways through which java supports polymorphism. Method overloading can be achieved by changing number of arguments or by changing the data type of arguments.

Overloading allows various methods to have the same name but multiple signatures, with the signature differing depending on the number of input arguments, the kind of input parameters, or both.

Advantage of method overloading:

We don't have to come up with new names for functions that do the same thing. If Java did not offer overload, we would have to generate method names like sum1, sum2,... or sum2Int, sum3Int,... etc., in our code.

Key points about method overloading:

  • When the function's data type is explicitly defined, overloading methods on return type are permitted.
  • Two or more static methods with the same name but different input parameters can exist.
  • In Java, we can't overload two methods that only differ by the static keyword.
  • In Java, we can overload main() just as other static methods.
  • Java does not support user-defined overloaded operators, unlike C++. Java overloads operators internally; for example, the + operator is overloaded for concatenation.

Example No.1:

Com.knowledge2life public class Main { static int Methodoverload(int x, int y) { return x + y; } static double Methodoverload(double x, double y) { return x + y; } public static void main(String[] args) { int myNum1 = Methodoverload(8, 5); double myNum2 = Methodoverload(4.3, 6.26); System.out.println("Knowledge2life: " + myNum1); System.out.println("Knowledge2life: " + myNum2); } }

OUTPUT:

Knowledge2life 13
Knowledge2life 10.559999999

Example No.2:

Com.knowledge2life public class Main { static int add(int a, int b) { return a+b; } static double add(double a, double b) { return a+b; } } class Overloading1 { public static void main(String[] args) { System.out.println("Knowledge2life " +Main.add(17,13)); System.out.println("Knowledge2life " +Main.add(10.4,10.6)); } }

OUTPUT:

Knowledge2life 30
Knowledge2life 21.0