Tutorials

Java Object Oriented Programming


Method Overloading


If a class declares multiple methods with the same name but with different number of parameters (or argument) then this scenario is known as method overloading.

Criteria for overloading

  • By changing the number of parameters (or arguments)

Multiply(int x, int y)

Multiply(int x, int y, int z)

Multiply()

All three are example of changing number of parameters in method Multiply(). Similarly you can keep adding parameters to overload more Multiply() methods.

 

  • By changing the data type of any individual or all parameters.

Multiply(int x, float y)

Multiply(int x, float y, int z)

Multiply(float x, float y, int z)

All three are example of changing data type of parameters. You can create any such combination to overload the method multiply.

 

Example

SourceOverloadMultiply.java


class OverloadMultiply {

      public void multiply(int x, int y){

            System.out.println(x*y);

      }

      public void multiply(int x, float y){

            System.out.println(x*y);

      }

      public void multiply(int x, int y, int z){

            System.out.println(x*y*z);

      }

      public void multiply(int x, double y,int z){

            System.out.println(x*y*z);

      }

}

Source: TestOverload.java


public class TestOverload{

      public static void main(String[] args) {

            OverloadMultiply om = new OverloadMultiply();

            om.multiply(3, 3.00F);  //parmeter int float

            om.multiply(5, 5);      //parameter int int

            om.multiply(6, 7.00, 2);//parameter int double int

      }

}

OUTPUT:

9.0

25

84.0

 

Advantage of overloading

Method overloading helps in improving the readability of the program code.

Suppose instead of providing common name multiply if we have used name A, B, C and D for our methods. In that case we needed to scan through the whole code to understand the purpose of each method.

Using proper name ‘multiply’ makes it clear that all methods would multiply given numbers. This increases readability of code.

 

What is not overloading?

Set 1: Example given below is not method overloading

public void multiply(int x, int y)

public void multiply(int a, int b)

 

Set 2: Example given below is not method overloading

public void multiply(int x, float y, int z)

public void multiply(int a, float y, int p)

 

Set 3: Example given below is not method overloading

public void multiply(int x, float y, int z)

public int multiply(int x, float y, int z)

 

Method overloading is not possible by just changing the return type of method. See Example of Set 3.

 

Why overloading is not possible by only changing the return type of a method?

Can we overload main() method in java?



Please Share this page
Views : 79
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!