Page 374 - Computer_Science_F5
P. 374

BigClass(int age) {
                          this.age = age;
                      }
                      // Code shows overloaded constructor                                         Chapter Five: Object oriented programming with Java
          FOR ONLINE READING ONLY
                      BigClass(int age, String name) {
                          // Code invokes the parameterised constructor using “this”
                          this(age);
                          this.name = name;
                      }
                      // method to show information
                      void show() {
                          System.out.println(“Name: “ + name + “, Age: “ + age);
                      }
                      public static void main(String[] args) {
                          // creating objects of BigClass
                          BigClass objX = new BigClass(35600);
                          BigClass objY= new BigClass(600, “Malaria”);


                          // calling show method to present information
                          objX.show();
                          objY.show();
                      }
                  }

               Output:





                                Figure 5.31: Output of "this" keyword in constructors


              The first constructor accepts an age parameter, while the second constructor takes
              both age and name parameters. To avoid repeating the initialisation logic, the second
              constructor uses the “this” keyword to invoke the first constructor and pass the age
              parameter. By doing this, you can eliminate the need for redundant code duplication.

               (iv) Used for passing current object as argument

              By using the “this” keyword, it is possible to pass the current instance of an object
              as an argument to another method. This is demonstrated in Program Example 5.30.

                                                    365
               Student’s Book  Form Five



     Computer Science Form 5.indd   365                                                     23/07/2024   12:34
   369   370   371   372   373   374   375   376   377   378   379