Java method Overloading Tutorial with example

Java method Overloading Tutorial with example

In a class Writing two or more methods with same name but different parameters is called method overloading.

Syntax:


Void add(inta,int b){};
Void add(float a ,float b){};

Rules to implement method overloading

  • methods must have different parameters.
  • in method overloading Return types can be same or different.
  • in method overloading access specifiers can be same or different.
  • methods may throw same or different Exceptions.

Advantages of method overloading

  • methods can be overloaded in the same class or in a sub class.
  • overloading means reusing the same method name,but with different parameters.
  • constructors can be overloaded.

Example


package com.javalschool;

public class OverloadDemo {

public void add(int a,int b){
System.out.println("The addition of two integers is:"+(a+b));
System.out.println("-------------");
}
public void add(int a,int b,int c){
System.out.println("The addition of Three inntegers is :"+(a+b+c));
}
public static void main(String[] args) {
OverloadDemo d = new OverloadDemo();
d.add(10, 20);
d.add(30, 56, 23);

}

}

Output


The addition of two integers is:30
-------------
The addition of Three inntegers is :109
-->