Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

What is the this keyword in Dart programming?

Maria Elijah

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

Why use the 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.

Example

The example below demonstrates how to use the this keyword to call an instance variable.

// Creating class Student
class Student {
// Creating instance variables
String matric_no;
int course;
// Creating a parameterized constructor
Student(String matricNo, int course_info){
// Calling instance variables using this keyword.
this.matric_no = matricNo;
this.course = course_info;
}
// Class method
void display_info(){
print("Student $matric_no is offerring $course courses this semester");
}
}
void main(){
// Creating instance of the class Student
// and assigning values
Student s1 = new Student("186HQ025", 10);
// Calling method
s1.display_info();
}

RELATED TAGS

dart
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring