Page 375 - Computer_Science_F5
P. 375

Computer Science  Java program to use this keyword for pasing current object
                Program Example 5.30:



               class MyClass {
          FOR ONLINE READING ONLY
                   int age;
                   //code shows  parameterised constructor
                   MyClass(int age) {
                       this.age = age;
                   }
                   //Code shows a method to display age
                   void displayAge() {
                       System.out.println(“Age: “ + this.age);
                   }
                   // method to pass a current object as argument
                   void myObject() {
                       methodTwo(this);
                   }
                   // method to receive the current object as an argument
                   void methodTwo(MyClass obj) {
                       System.out.print(“See age from object: “);
                       obj.displayAge();
                   }
                   public static void main(String[] args) {
                       // creating an object of MyClass
                       MyClass obj = new MyClass(5700);
                       // code invoke myObject method
                       obj. myObject();
                   }
               }


             Output:



                           Figure 5.32: Output showing "this" keyword passing objects


           The myObject() method  invokes methodTwo() and provides the current  object
           (referred to as “this”) as an argument. Inside methodTwo(), you can receive the
           current object as an argument and proceed to call the displayAge() method, which
           prints the age of an object.

                                                 366
                                                                for Advanced Secondary Schools



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