Method Overloading in Java

Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call
Below is an example of a class demonstrating Method Overloading:

public class MethodOverloadDemo
         {
            void sumOfParams()
            {
                // First Version
                System.out.println("No parameters");
            }
            void sumOfParams(int a)
            {
                 // Second Version
                System.out.println("One parameter: " + a);
             }
            int sumOfParams(int a, int b)
            {
                // Third Version
                System.out.println("Two parameters: " + a + " , " + b);
                return a + b;
             }
             double sumOfParams(double a, double b)
             {
                // Fourth Version
                System.out.println("Two double parameters: " + a + " , " + b);
                return a + b;
            }
             public static void main(String args[])
            {
                MethodOverloadDemo moDemo = new MethodOverloadDemo();
                int intResult;
                double doubleResult;
                moDemo.sumOfParams();
                System.out.println();
                moDemo.sumOfParams(2);
                System.out.println();
                intResult = moDemo.sumOfParams(10, 20);
                System.out.println("Sum is " + intResult);
                System.out.println();
                doubleResult = moDemo.sumOfParams(1.1, 2.2);
                System.out.println("Sum is " + doubleResult);
                System.out.println();
             }
        }

Output:
No parameters
One parameter: 2
Two parameters: 10 , 20
Sum is 30
Two double parameters: 1.1 , 2.2
Sum is 3.3000000000000003

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More