×

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 super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.

Dart Method Overriding

Before understanding method overriding, it is important to clear the concept of polymorphism. Polymorphism is derived from two Greek words 'Poly' which means many and 'morphs' which means many forms....

5 minutes read.

Dart Numbers

Dart provides an in-built data type ‘Numbers’ that provides two types of values: intdouble 1. int data type int data type supports integer values, and their size or values range is platform-dependent. Integers...

4 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 Object-Oriented Concepts

Dart is a programming language that supports object-oriented programming. It is focused on the objects that are real-world entities and supports all the concepts of OOPS, such as objects, classes,...

4 minutes read.

Dart Single-Page Application Architecture

In a single page application architecture, the source code for a single web page loads the entire application. The responsibility of building the user interface and requesting data from the...

2 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.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 minutes read.

Assert in DART

In any programming language, resolving error is the most unwanted and tedious task. At times it becomes very difficult to find the error in the large code. Dart offers an...

3 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 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 Switch Case Statement

In the case of if-else statements, we prefer not to use the if-else ladder when there are many test conditions to be evaluated. In such a situation, it is preferable...

4 minutes read.

Dart Construtors

Constructors are the very important concept in any programming language. They are the special functions created in the classes to allocate memory to the objects of that class when created...

4 minutes read.

Dart Generators

Synchronous Generator Dart Generator is a unique function that allows us to generate price sequences. Generators return values when needed; means that the value is generated if we try to duplicate...

5 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.

Dart - extends, with and implements Keywords

The application development in Dart programming language using the Flutter framework, regularly experience different usage of the implements, extends and with keywords. Dart has full support for inheritance that is...

5 minutes read.

Dart Logical Operators

Logical operators are the operators that combine two or more conditions, and accordingly return a Boolean value : true or false. Assume the value of variable A is 25 and B...

2 minutes 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 Variables

Variables are used to store the value of a particular data type referred to in the whole program by a name or identifier. They refer to a memory location as...

5 minutes read.

Dart Booleans

Booleans Dart has a data type named ‘bool’ to represent Boolean values : true and false, which are compile-time constants. ‘True’ or ‘False’ cannot be assigned with values 1 or 0. Example, bool...

1 minute read.