Page 355 - Computer_Science_F5
P. 355

Computer Science  (b) Creating an object
           An object is created from a class in Java. From the previous class “Main”, objects
           can be created as it is shown in the following Program Example 5.15 by specifying
           the class name and object name. The object is created using the keyword “new”:
          FOR ONLINE READING ONLY
                    Program Example 5.15:

            Java program to create an object myDemo

              public class Main2 {
                     int x = 116;
                  public static void main(String[] args) {
                  Main2 myDemo = new Main2();
                  System.out.println(myDemo.x); //This print the value of x, where the object created
                                                                     //access the attribute from the main class
                }
              }

             Output:



                                      Figure 5.16: Creating an object

           (c) Creating multiple objects
           Multiple objects can be created in Main2 class as it is shown in Program Example
           5.16.

                    Program Example 5.16:

            Java program to create multiple objects

              public class Main2 {
                  int x = 116; int y = 556;
                  public static void main(String[] args) {
                      Main2 myDemo1= new Main2(); // This code creates the Object 1
                      Main2 myDemo2= new Main2(); // This code creates the Object 2
                      System.out.println(myDemo1.x);
                      System.out.println(myDemo2.y);
                      }
                }

             Output:




                                   Figure 5. 17: Creating multiple objects


                                                 346
                                                                for Advanced Secondary Schools



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