×

Dart this Keyword

The ' this ' keyword, similar to that in Java and C#, refers to an object of the class using it. It points to the current object of the class, methods, or constructor. 

To understand the use case of the ' this ' keyword, let us assume if the class attributes and parameter names in a program are the same. This arises ambiguity, which can be resolved using this keyword. The ' this ' keyword prefixes the class attributes. It can also be passed as a parameter in the member function or constructors or can be used to call them ( of the current class ). 

Example 1 :

Consider the following examples in Dart that explain the concept of the 'this' keyword.

// Definition of the class ' employee '
class employee 
{
  // declaration of data members ‘ emp_id ’ and ‘ emp_name ’
  var emp_id ;
  var emp_name ;
  // definition of constructor employee( )
  employee( var emp_id, var emp_name ) 
{
    /* accessing the data members of the class 
       using ' this ' keyword */
    this.emp_id = emp_id ;
    this.emp_name = emp_name ;
    print( " This is an example of ' this ' keyword : " ) ;
    // printing the value of emp_id
    print( " The employee id is : " ) ;
   
    print( emp_id ) ;
    // printing the value of emp_name
    print( " The name of the employee is : " ) ;
    print( emp_name ) ;
  }
}
void main( ) 
{
  // passing arguments to the constructor 
  employee e1 = new employee( 1 , ' Yukta ' ) ;
}

Output :

Dart this Keyword

Explanation :

In the above program, we created a class called ‘ employee ’ that has two attributes, ' emp_id ' and ' emp_name '. We assigned the values to these attributes by creating a constructor and passing parameters the same as the class attributes name. The ' this ' pointer refers to the attributes and assigning the value. 

The Dart compiler gets confused if there are a number of the parameters with the same name. This is the case of ambiguity. The ' this ' keyword is used to refer to the current class object to resolve this ambiguity.

Points to Remember

  • The ' this ' keyword is used to point to the object of the class invoking it.
  • It can be used to refer to the present class variables.
  • We can instantiate or invoke the current class constructor using this keyword.
  • We can pass the ' this ' keyword as a parameter in the constructor call.
  • We can pass the ' this ' keyword as a parameter in the method call.
  • It removes the ambiguity or naming conflict in the constructor or method of our instance/object.
  • It can be used to return the current class instance.

Example 2 :

Consider another example to have a better understanding of ' this ' keyword :

Case 1 : When the name of the local variable is the same as that of the name of the member

// definition of the class called ‘ Test ’
class Test
{
   // data member ' x ' declaration
   var x ;
   // defintion of member function setX( ) to set the value of x
   void setX ( var x )
   {
       // The ' this ' pointer is used to retrieve the object's x
       // hidden by the local variable ' x '
       this.x = x ;
   }
   /* definition of member function display( ) to display the value
      of variable x */
   void display( ) 
   { 
     print( " The value of x is : " ) ;
     print( x ) ;
   }
}
 int main( )
{
   // declaring an object named ' t '
   var t = new Test( ) ;
   // local variable ' x ' ( same name as that of data member ' x ' of 
   // class ' Test ')
   int x = 20 ;
   // accessing member functions of the class using object 
   t.setX( x ) ;
   t.display( ) ;
   return 0 ;
} 

Output :

Dart this Keyword

Case 2: To return a reference to the calling object

// definition of class ' Test '
class Test 
{
  // data member declaration
  var x ;
  var y ;
  // definition of member function setX( ) with a return
  // type of class and a single argument a of integer type
  Test setX( int a ) 
  {
    x = a ;
    return this ;
  }
  // definition of member function setY( ) with a return
  // type of class and a single argument a of integer type
  Test setY( int b ) 
  {
    y = b ;
    return this ;
  }
  // definition of member function display( ) to display the values of x and y
  void display( ) 
  {
    print( " The value of x is : " ) ;
    print( x ) ;
    print( " The value of y is : " ) ;
    print( y ) ;
  }
}
int main( ) 
{
  // creating an object of the class ‘ t ’
  var t = new Test( ) ;


  // accessing the member functions of the class using
  // the object of the class
  t.setX( 10 ).setY( 20 ) ;
  t.display( ) ;
  return 0 ;
}

Output :

Dart this Keyword

Local Variables :

Local variables are the variables that are local to the method, constructor, or block in which they are defined. The scope of this variable is only inside these identifiers. These local variables can not be used outside the function, constructor, or block in which they are defined. 

Class Variables :

Class variables are the variables that are declared inside the class but outside the constructor, method, or block. These are also known as the static data members that are declared using the 'static' keyword. Some points to remember here are that : 

Only a single copy of the static class variable is declared. 

All the objects share this single copy of the variable only. 

Instance Variables :

All the variables are other than class variables are known as is instance variables. It can be said that the variables declared without the 'static' keyword are instance variables. These variables are object-specific, which means for each object, they have a separate value, and they can be accessed using the instance of that class.

Difference Between Class Variable and Instance Variable :

Here are a few points of difference between class variable and instance variable

Sr.Class VariablesInstance Variables
1.The class variables are declared using the ' static ' keyword in a class. They are not declared in the function or constructor.The instance variables are the variables other than the static variables. These variables are declared in a class without using the ' static ' keyword.
2.The class variables can be accessed using the class name.  Syntax : ClassName.variableNameThe instance variables can be accessed using the object of that class.  Syntax : ObjectRefernce.variableName
3All the class variables are common to all the objects of that class as they share only one copy of this static variable.The instance variables are not common to all instances of the class. Each object will preserve its own copy of the instance variables.
4These are created when the program is started and destroyed when the program is terminated. The scope of the static variables is throughout the lifetime of the program.The instance variables are created when an object of the particular class is created using the new( ) keyword and destroyed when the object is destroyed.

Related Topics

Dart Miscellaneous Operators

Apart from the operators we studied so far, Dart provides some more operators which are as follows : Conditional OperatorCascade Notations Conditional Operators These are the operators that help in evaluating the expression...

1 minute read.

Dart Break and Continue

Loop statements are used to change the normal sequence of flow of the program. Dart supports two types of loop control statements: Break StatementContinue Statement Break Statement : The ‘ break ’ statement is...

4 minutes read.

Dart If statement

If statement is used to set the control on the lines of code. Using if statement, block of code is executed only if the expression in the statement returns true....

1 minute read.

Dart Queues

A queue is a user-defined collection of data. It is based on the FIFO principle ( First In First Out ) which implies that the element to be inserted first,...

3 minutes read.

Dart Symbols

Symbols data type in Dart A symbol is an object that is the representation of an operator or identifier in Dart. These are compile-time constants.  They are used in APIs that refer...

1 minute read.

C++ vs Dart

Difference between C++ and Dart C++ is an object-oriented programming language developed in 1980 by Bjarne Stroustrup. It has wide real-world applications with various in-built functions and a very vast library...

1 minute read.

Dart Isolates

Dart successfully supports asynchronous programming which runs our program without any hindrance. This asynchronous programming is used to achieve concurrency. Dart supports concurrent programming with features such as ‘ async-await...

9 minutes read.

Dart If-else statement

In the previous section, we studied about if statements in detail. If – block is executed when the condition evaluates to true, else if the condition evaluates to false, then...

1 minute read.

Dart Exception Handling

Exception Class – An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught...

4 minutes read.

Dart Anonymous Function

Dart functions are the user defined functions that are designed to perform specific task. The use case of the functions is that they can be directly called any number of...

3 minutes read.

Golang vs Dart

Go is the procedural programming language. It was founded in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but was launched in 2009 as the language of...

2 minutes read.

Dart Bitwise and Shift Operators

The Bitwise operators are the operators that perform different operations bit by bit on the value of the two operands. List of Bitwise Operators in Dart Sr. Operators Description 1. & ( Binary AND ) It returns...

2 minutes read.

Dart Basics

Dart, as earlier mentioned multiple times, is very similar to C, C++ and Java. It is an object-oriented, garbage collecting and class-based programming language. Let’s look further and see what Dart has...

10 minutes read.

Unit Testing in Dart

Typing testing ensures that your app keeps working as you add more features or change existing functionality. Unit testing helps to confirm the behavior of a single function, method, or...

4 minutes read.

Common Collection Methods

Most of the programming languages have arrays as a way to list items together. However, Dart has a collection of data structures similar to array. These are supported by the...

3 minutes read.

Dart Maps

Map is an object-based data structure that associates keys and values that can be of any data type. Every key can occur only once, while the values can be used multiple...

5 minutes read.

Dart Generics

Dart Generics is similar to Dart collections, which are used to store homogeneous data. As we have discussed in Dart's features, it is a language with types being optional. By default,...

4 minutes read.

Dart Type Test Operators

Type Test Operators in Dart These operators are used to check the types of expressions at runtime. Dart is a typed language, and we often want to assert that a value...

1 minute read.

Builder Classes in Dart

Before understanding builder classes, let us understand about Flutter that makes the best use of the builder classes. Flutter is actually not a programming language, it is a software development...

6 minutes read.

Dart Optional Parameters

Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not...

2 minutes read.