Page 373 - Computer_Science_F5
P. 373
Computer Science Programe Exampe 5.28:
Java code using this keyword for getters and setters
class MyClass {
String word;
FOR ONLINE READING ONLY
// setter method
void setWord( String word ) {
this.word = word;
}
// getter method
String getWord(){
return this.word;
}
public static void main( String[] args ) {
MyClass obj = new MyClass();
// calling the setter and the getter method
obj.setWord(“Usimbaji Mubashara”);
System.out.println(“obj.word: “+obj.getWord());
}
}
Output:
Figure 5.30: Output of "this" keyword used with getters and setters
(iii) Used in constructor overloading
When dealing with constructor overloading, there may be instances where you need
to call one constructor from another. However, it is important to note that you cannot
directly invoke a constructor. Instead, you can employ the “this” keyword for this
purpose. Program Example 5.29 elaborates.
Program Example 5.29:
Java program to use this keyword for constructors
class BigClass {
//code shows instance variables
int age;
String name;
// code shows parameterised constructor
364
for Advanced Secondary Schools
Computer Science Form 5.indd 364 23/07/2024 12:34

