Page 229 - Computer science 868 Class 12
P. 229

8.2 USER-DEFINED METHOD
                 According to the requirement of the program, sometimes programmers need to create their own methods for the
                 easiness of the program. These methods are known as user-defined methods.

                 Let us take an example.
                    class perfect_number
                    {
                         public static void main (int num)
                         {
                              perfect(num); // Method call
                         }
                         public static void perfect(int n) //user-defined method
                         {
                              int i,s=0;
                              for(i=1;i<=n;i++)
                              {
                                  if(n%i==0)
                                  {
                                       s=s+i;
                                  }
                              }
                              if(s==n)
                                  System.out.println(n+" is perfect number");
                              else
                                  System.out.println(n+" is not perfect number");
                        }
                    }
                 In the above method, perfect(int) is the user-defined method. When called, it checks whether the number is a perfect
                 number or not and prints a suitable message.

                 Methods act as an abstraction for complex user-defined operations on objects. Abstraction hides the implementation
                 details and exposes only the necessary functionality of the object. This helps the programmers to use complex logic
                 inside a method without understanding how it has been implemented. It hides the internal details from the outside
                 world so that we only need to know the job of the program code without knowing how the method works.


                     8.3 DIFFERENT PARTS OF A METHOD
                 The various parts of a method are as follows:
                 •  Header
                 •  Method Signature

                 •  Access Specifier
                 •  Return Type and Return Statement
                 •  Method Name

                 •  Parameter List
                 •  Body of the Method





                                                                                                                       227
                                                                                                            Methods    227
   224   225   226   227   228   229   230   231   232   233   234