***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***

posts

    Method Overloading

    If a class has multiple methods with same name but differ in type or number of parameters, is known as Method Overloading.

    Method overloading increases the readability of the program.

    There are two ways to overload the method in java

    1. By changing number of arguments
    2. By changing the data type

    Example:

    class mOverload{

    static int add(int x, int y) {

      return x + y;

    }

    static double add(double x, double y) {

      return x + y;

    }

    public static void main(String[] args) {

      int myNum1 = add(8, 5);

      double myNum2 = add(4.3, 6.26);

      System.out.println("int: " + myNum1);

      System.out.println("double: " + myNum2);

    }

    }

    In the above example, there are two methods with same name (add), but the methods differ in type of parameters. One method is used to add integers and other method is used to add floating point numbers.

    When a call is made in the main method, depending on the type of arguments the corresponding method will be called. If no match is found error is raised.

    No comments:

    Post a Comment