Default Constructor
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 10 of 110.
When you don't define any constructor in a class, Dart automatically provides a default constructor. This is a constructor with no parameters that simply creates an instance of the class.
class Book {
String title = 'Unknown';
int pages = 0;
}
// Dart provides a default constructor: Book()
Book myBook = Book();
print(myBook.title); // UnknownThe default constructor is invisible in your code, but it exists. It takes no arguments and initializes the object with whatever default values you've assigned to the instance variables.
Once you define your own constructor, the default constructor is no longer provided automatically. If you still want a no-argument constructor alongside a parameterized one, you must explicitly create it:
class Book {
String title;
int pages;
// Explicit default constructor
Book() : title = 'Unknown', pages = 0;
// Parameterized constructor
Book.withDetails(this.title, this.pages);
}
Book book1 = Book(); // Uses default
Book book2 = Book.withDetails('Dart', 300); // Uses parameterizedThe explicit default constructor uses an initializer list (the part after the colon) to set initial values. This pattern is useful when you want to offer multiple ways to create objects from the same class.
Challenge
EasyLet's build a simple product inventory system that demonstrates both implicit and explicit default constructors.
You'll create two files to organize your code:
product.dart: Define aProductclass that offers two ways to create products:- An explicit default constructor
Product()that initializesnameto'Unnamed'andpriceto0.0using an initializer list - A named constructor
Product.withDetailsthat acceptsnameandpriceparameters - A
display()method that prints:Product: [name] - $[price]
- An explicit default constructor
main.dart: Import your product class and create two products:- One using the default constructor
- One using the named constructor with
'Laptop'and999.99
display()on each product.
Your Product class should have two instance variables:
String namedouble price
Expected output format:
Product: Unnamed - $0.0
Product: Laptop - $999.99Cheat sheet
When no constructor is defined in a class, Dart automatically provides a default constructor with no parameters:
class Book {
String title = 'Unknown';
int pages = 0;
}
Book myBook = Book(); // Uses implicit default constructor
print(myBook.title); // UnknownOnce you define your own constructor, the default constructor is no longer provided automatically. To have both a no-argument constructor and a parameterized one, you must explicitly create them:
class Book {
String title;
int pages;
// Explicit default constructor with initializer list
Book() : title = 'Unknown', pages = 0;
// Named constructor
Book.withDetails(this.title, this.pages);
}
Book book1 = Book(); // Uses default
Book book2 = Book.withDetails('Dart', 300); // Uses named constructorThe explicit default constructor uses an initializer list (after the colon) to set initial values.
Try it yourself
import 'product.dart';
void main() {
// TODO: Create a product using the default constructor
// TODO: Create a product using the named constructor with 'Laptop' and 999.99
// TODO: Call display() on each product
}
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