While super keyword is used to call parent class, this keyword is used to call the class itself.
In below I am writing one example which display use of this keyword.
void main()
{
var keywordThis = thisKeyword();
keywordThis..printFunction(100 , 200);
}
class thisKeyword
{
int x = 15; //Global Variable
int y = 20; //Global Variable
void printFunction(int x , int y) // Local Variable
{
//Without Using this keyword
print("The Value of X : $x and The value of Y : $y");
x = this.x;
y = this.y;
//Using this keyword
print("The Value of X : $x and The value of Y : $y");
//we can also write this type using this keyword
//print("The Value of X : ${this.x} and The value of Y : ${this.y}");
}
}
In the main() function:
An instance of the thisKeyword
class is created and assigned to the variable keywordThis
.
The printFunction
method of the thisKeyword
class is called on keywordThis
with arguments 100 and 200.
In the printFunction
method of the thisKeyword class:
Initially, the method receives parameters x and y, which are local variables.
The method first prints the values of x and y without using the this keyword. These values are the arguments passed to the method (100 and 200).
Then, the method assigns the values of the instance variables x and y (which are 15 and 20, respectively) to the local variables x and y using the this keyword. Finally, it prints the values of x and y again after the assignment.
Output:
The Value of X : 100 and The value of Y : 200
The Value of X : 15 and The value of Y : 20