Page 354 - Computer_Science_F5
P. 354

(iii) Parameters: Functions can receive       function has been called and the
                   inputs, called parameters that provide   returned result will be stored in the
                   data to work with. Parameters are        SquareArea to provide output
                   declared within parentheses after
                   the function name.                                                              Chapter Five: Object oriented programming with Java
          FOR ONLINE READING ONLY
                   Recalling from Program Example      Java Classes and Objects
                   5.14, In the main method, the       In Java, everything is tied to classes and
                   computeSquareArea function is       objects, each carrying attributes  and
                   called  with an argument of 25, which  methods. For instance, imagine a car as
                   represents the Length of the square.  an object with attributes such as weight

              (iv)  Calling functions: A code can be   and color, and actions like drive and
                   executed within a function  calling it   brake which are the method as it was
                   by its name, followed by parentheses  elaborated  earlier in previous sections.
                   that may include parameters.        In this case, a class serves as a blueprint
                   In this program example, the        for creating objects, similar to an object
                   “calculateSquareArea(25)”           constructor.



              (a) Creating a class
              When you want to create a class, the keyword “class” is used. You have to declare
              a class using the class keyword, followed by a unique identifier to name it. The
              class body is then enclosed within a pair of opening and closing braces “{  }”. This
              structure is shown in a syntax below:
              class Identifier
                  {
                   //The code for class body will be written here
                  }
                  The following example declares a class named Animal:
                  class Animal
                  {
                   // The code for class body will be written here
                  }

              From the above example the of class “Animal”, a class body should be occupied
              with fields, methods, and constructors. The class body can be filled with variety of
              elements. The following example shows how you can create a class named “Main”
              with variable “x”:

                   public class Main {
                     int x = 116;
                   }


                                                    345
               Student’s Book  Form Five



     Computer Science Form 5.indd   345                                                     23/07/2024   12:34
   349   350   351   352   353   354   355   356   357   358   359