Page 207 - computer science (868) class 11
P. 207

methods (with the same names) should have either.
                 •  Different type of parameters, or
                 •  Different number of parameters
                 Let us consider the following program.

                  Program 5      Write a program using a function called area() to compute the area of a:
                                 a.  Circle – takes radius as a parameter as double data type.
                                 b.  Square – takes side as a parameter as int data type.
                                 c.  Rectangle – takes length and breadth as the parameters as int data types.


                   1      class function_overloading
                   2      {

                   3          void area(double r)
                   4          {

                   5              double ar=3.142 * r * r;
                   6              System.out.println("The Area of a circle "+ ar);
                   7          }

                   8          void area(int s)

                   9          {
                  10              int ar=s * s;
                  11              System.out.println("The Area of a Square "+ ar);

                  12          }
                  13          void area(int l, int b)

                  14          {
                  15              int ar=l * b;

                  16              System.out.println("The Area of a rectangle "+ ar);
                  17          }

                  18          void main()
                  19          {

                  20              area(5.6);
                  21              area(5,2);

                  22              area(5);
                  23          }

                  24      }

                 The output of the preceding program is as follows:
                   The Area of a circle 98.53311999999998
                   The Area of a rectangle 10
                   The Area of a Square 25



                                                                                                                       205
                                                                                              Methods and Constructors  205
   202   203   204   205   206   207   208   209   210   211   212