Page 372 - Computer_Science_F5
P. 372

class MyClass {                    In the piece of code provided, both the
                        // lines show instance variable  instance variable and the parameter are
                                                       named “length.” This creates ambiguity
                        int length;                    for the Java compiler. To resolve such      Chapter Five: Object oriented programming with Java

                        // lines show parameter        ambiguity, you can  use the  “this”
          FOR ONLINE READING ONLY
                                                       keyword. When you write and run the
                        MyClass(int length){
                                                       above codes without this keyword you
                            length = length;           may get ambiguous output such as zero

                        }                              or other. Program Example  5.27 shows
                                                       the  use of this keyword, the  output is
                    }                                  shown in Figure 5.29.

                        Programe Exampe 5.27:

               Java code using this keyword for ambiguous variable names

                 class MyClass {
                     // lines show instance variable

                     int length;
                     // lines show parameter
                     MyClass(int length){
                         this.length = length;

                     }
                     public static void main(String[] args) {
                         MyClass obj = new MyClass(23);
                         System.out.println(“obj.length = “ + obj.length);
                     }

                 }



                Output:




                                     Figure 5.29: Output of ambiguous variable


              (ii) Used in getters and setters methods

              In these methods, this keyword is used to assign value inside the setter method and
              also to access value inside the getter method as shown in Program Example 5.28.

                                                    363
               Student’s Book  Form Five



     Computer Science Form 5.indd   363                                                     23/07/2024   12:34
   367   368   369   370   371   372   373   374   375   376   377