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 Sedanthis 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
EasyComplete 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 theCarclass where you'll add thedisplayInfomethoddriver.dart: Sets variables on a car object and callsdisplayInfo()(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();
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor