Redirecting Constructors
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 15 of 110.
A redirecting constructor delegates to another constructor in the same class. Instead of initializing fields directly, it calls a different constructor to do the work. This helps avoid code duplication when multiple constructors share similar logic.
The syntax uses a colon followed by this and the target constructor:
class Point {
int x;
int y;
// Main constructor
Point(this.x, this.y);
// Redirecting constructor - delegates to main constructor
Point.origin() : this(0, 0);
// Another redirecting constructor
Point.onXAxis(int x) : this(x, 0);
}When you call Point.origin(), it redirects to Point(0, 0), which handles the actual initialization. The redirecting constructor cannot have a body or an initializer list - it simply passes control to another constructor.
Point p1 = Point(3, 5);
Point p2 = Point.origin();
Point p3 = Point.onXAxis(7);
print('p1: (${p1.x}, ${p1.y})'); // p1: (3, 5)
print('p2: (${p2.x}, ${p2.y})'); // p2: (0, 0)
print('p3: (${p3.x}, ${p3.y})'); // p3: (7, 0)Redirecting constructors are useful when you want to provide convenient shortcuts for common object configurations while keeping all initialization logic in one place. If you later need to change how objects are initialized, you only update the main constructor.
Challenge
EasyLet's build a time representation system that uses redirecting constructors to provide convenient ways to create time objects.
You'll create two files to organize your code:
time_of_day.dart: Define aTimeOfDayclass that represents a time with hours and minutes. Your class should have:- Two instance variables:
int hoursandint minutes - A main constructor that takes both
hoursandminutes - A redirecting constructor
TimeOfDay.midnight()that creates a time at 0:00 - A redirecting constructor
TimeOfDay.noon()that creates a time at 12:00 - A redirecting constructor
TimeOfDay.atHour(int hour)that creates a time at the specified hour with 0 minutes - A
display()method that prints the time
- Two instance variables:
main.dart: Import your time class and create four time objects:- A custom time at 9:30 using the main constructor
- Midnight using the
midnight()constructor - Noon using the
noon()constructor - A time at 17:00 using the
atHour()constructor
display()on each time in the order listed above.
The display() method should print in this exact format, with hours and minutes zero-padded to two digits:
[HH]:[MM]For example, 9 hours and 5 minutes should display as 09:05.
Expected output:
09:30
00:00
12:00
17:00Cheat sheet
A redirecting constructor delegates to another constructor in the same class using this. It helps avoid code duplication by calling a different constructor to handle initialization.
Syntax uses a colon followed by this and the target constructor:
class Point {
int x;
int y;
// Main constructor
Point(this.x, this.y);
// Redirecting constructor - delegates to main constructor
Point.origin() : this(0, 0);
// Another redirecting constructor
Point.onXAxis(int x) : this(x, 0);
}When calling Point.origin(), it redirects to Point(0, 0). Redirecting constructors cannot have a body or initializer list.
Point p1 = Point(3, 5);
Point p2 = Point.origin();
Point p3 = Point.onXAxis(7);
print('p1: (${p1.x}, ${p1.y})'); // p1: (3, 5)
print('p2: (${p2.x}, ${p2.y})'); // p2: (0, 0)
print('p3: (${p3.x}, ${p3.y})'); // p3: (7, 0)Try it yourself
import 'time_of_day.dart';
void main() {
// TODO: Create a custom time at 9:30 using the main constructor
// TODO: Create midnight using the midnight() constructor
// TODO: Create noon using the noon() constructor
// TODO: Create a time at 17:00 using the atHour() constructor
// TODO: Call display() on each time in the order listed above
}
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