Constructor Basics
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 8 of 110.
A constructor is a special method that runs automatically when you create a new object. It initializes the object's instance variables right at the moment of creation.
Here is an example of a class with a constructor:
class Dog {
String name;
String breed;
Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
}The constructor has the same name as the class. Parameters are passed when creating the object.
Create objects by passing arguments to the constructor:
Dog rex = Dog('Rex', 'German Shepherd');
Dog buddy = Dog('Buddy', 'Golden Retriever');Access the variables set by the constructor:
print(rex.name);
print(rex.breed);
print(buddy.name);
print(buddy.breed);Output:
Rex
German Shepherd
Buddy
Golden RetrieverDart also offers a shorthand constructor syntax using this.variableName directly in the parameter list:
class Dog {
String name;
String breed;
// Shorthand: automatically assigns parameters to instance variables
Dog(this.name, this.breed);
}Both versions produce the same result. The shorthand is a popular Dart feature that removes the need to write this.name = name manually.
You can also add default parameter values:
class Cat {
String name;
int age;
Cat(this.name, [this.age = 1]); // age defaults to 1
}
Cat fluffy = Cat('Fluffy', 3);
Cat whiskers = Cat('Whiskers'); // age defaults to 1
print('${fluffy.name} is ${fluffy.age}'); // Fluffy is 3
print('${whiskers.name} is ${whiskers.age}'); // Whiskers is 1Key Point: Constructors ensure every object is properly initialized with data at the moment it is created, saving you from manually setting variables afterwards.
Challenge
EasyYou are given PHP files (book.dart and driver.dart) to implement a book system.
Your tasks:
- Complete the
Bookclass inbook.dartby adding a constructor that initializestitle,author, andpages— use the Dart shorthand syntaxBook(this.title, this.author, this.pages); - In
driver.dart, create aBookobject for'Harry Potter'by'J.K. Rowling'with400pages
Follow the TODO comments in each file.
Cheat sheet
A constructor is a special method that runs automatically when you create a new object. It initializes the object's instance variables at the moment of creation.
The constructor has the same name as the class:
class Dog {
String name;
String breed;
Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
}Create objects by passing arguments to the constructor:
Dog rex = Dog('Rex', 'German Shepherd');Dart offers a shorthand constructor syntax using this.variableName directly in the parameter list:
class Dog {
String name;
String breed;
Dog(this.name, this.breed);
}You can add default parameter values using optional positional parameters:
class Cat {
String name;
int age;
Cat(this.name, [this.age = 1]); // age defaults to 1
}
Cat fluffy = Cat('Fluffy', 3);
Cat whiskers = Cat('Whiskers'); // age defaults to 1Try it yourself
import 'book.dart';
void main() {
// TODO: Create a Book object with:
// title: 'Harry Potter', author: 'J.K. Rowling', pages: 400
Book myBook = ?;
print("'${myBook.title}' by ${myBook.author}, ${myBook.pages} pages");
}
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