Skip to main content

Command Palette

Search for a command to run...

Dart: This Keyword

Published
2 min read
Dart: This Keyword

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

Dart

Part 50 of 50

I'll be here to provide explanations, examples, and assistance as you explore the depths of Dart programming language. Together, we'll unravel the intricacies of Dart, from its fundamental concepts to

Start from the beginning

Dart Packages

In simple terms, Dart packages are collections of reusable code that are created by developers to help others solve common problems or perform specific tasks when building applications with the Dart programming language. Think of Dart packages like t...

More from this blog

Flutter Journey with Jinali

141 posts