The this
keyword is used to refer to the current class instance. this
can be used to invoke the current class’s constructors or methods. It also helps access the current class’s instance variables.
The this
keyword can be used to set the instance variable’s values or get the current instance of the class.
this
keyword?Suppose the declared class attributes are the same as the parameter name, and the program becomes ambiguous. We can eliminate this ambiguity by prefixing the class attributes with the this
keyword.
The this
keyword can be given as an argument to the constructors or methods of the class.
The example below demonstrates how to use the this
keyword to call an instance variable.
// Creating class Studentclass Student {// Creating instance variablesString matric_no;int course;// Creating a parameterized constructorStudent(String matricNo, int course_info){// Calling instance variables using this keyword.this.matric_no = matricNo;this.course = course_info;}// Class methodvoid display_info(){print("Student $matric_no is offerring $course courses this semester");}}void main(){// Creating instance of the class Student// and assigning valuesStudent s1 = new Student("186HQ025", 10);// Calling methods1.display_info();}