Menu
Coddy logo textTech

The this Keyword

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 5 of 110.

The this keyword refers to the current instance of a class. Inside a method, this lets you access the object's own variables.

Here is an example of a class with methods using this:

class Car {
  String color = '';
  String model = '';

  void honk() {
    print('Beep beep!');
  }

  void describe() {
    print('I am a ${this.color} ${this.model}');
  }
}

Inside describe(), this.color and this.model refer to that specific object's variables.

Create a car object and set its variables:

Car myCar = Car();
myCar.color = 'Red';
myCar.model = 'Sedan';

Call the methods:

myCar.honk();
myCar.describe();

Output:

Beep beep!
I am a Red Sedan

this is especially useful when a method parameter has the same name as an instance variable:

class Car {
  String color = '';

  void setColor(String color) {
    this.color = color; // this.color = instance variable, color = parameter
  }
}

Without this, Dart would not know whether color refers to the parameter or the instance variable. Key Point: this always refers to the specific object that is currently calling the method.

challenge icon

Challenge

Easy

Complete the Car class in car.dart by adding a method called displayInfo that uses the this keyword to print the car's year, make, and model in the format:

'This car is a [year] [make] [model]'

  • car.dart: Contains the Car class where you'll add the displayInfo method
  • driver.dart: Sets variables on a car object and calls displayInfo() (locked)

Cheat sheet

The this keyword refers to the current instance of a class and allows you to access the object's own variables inside methods.

Using this in a method:

class Car {
  String color = '';
  String model = '';

  void describe() {
    print('I am a ${this.color} ${this.model}');
  }
}

this is especially useful when a method parameter has the same name as an instance variable:

class Car {
  String color = '';

  void setColor(String color) {
    this.color = color; // this.color = instance variable, color = parameter
  }
}

Without this, Dart would not know whether color refers to the parameter or the instance variable.

Try it yourself

import 'car.dart';

void main() {
  Car myCar = Car();
  myCar.year = '2020';
  myCar.make = 'Toyota';
  myCar.model = 'Corolla';
  myCar.displayInfo();
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming