Method Overloading in Java
Overview
Method overloading in Java is a feature that allows a class to have more than one method having the same name, with different method signatures. It is similar to constructor overloading in java which allows a class to have more than one constructor having different argument lists.
Method signature = method return type + method name + method paramters
For example, if we take the argument list having two parameters i.e add(int a, int b) is different from the argument list with three parameters i.e add(int a, int b, int c).
They are two ways of method overloading
1.Changing the number of arguments
2.Changing the return data type
Code Listing
package com.testingdocs.tutorial; //MethodOverloadingDemo.java public class MethodOverloadingDemo { public static void main(String[] args) { MethodOverloadingDemo mDemo = new MethodOverloadingDemo(); System.out.println("Integer overloaded method ="+ mDemo.add(1, 5)); System.out.println("Double overloaded method ="+ mDemo.add(2.5, 3.5)); System.out.println("String overloaded method ="+ mDemo.add("Testing", "Docs")); } //Overloaded methods public int add(int a,int b) { return a+b; } public double add(double a,double b) { return a+b; } public String add(String s1,String s2) { return s1.concat(s2); } }
Screenshot
Sample Output
Integer overloaded method =6
Double overloaded method =6.0
String overloaded method =TestingDocs