Constructors & Inheritance
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 41 of 110.
When a child class extends a parent, the parent's constructor must be called to properly initialize inherited fields. Dart provides flexible ways to handle this through the initializer list using super.
If the parent has a parameterized constructor, the child must call it explicitly:
class Person {
String name;
int age;
Person(this.name, this.age);
}
class Student extends Person {
String school;
Student(String name, int age, this.school) : super(name, age);
}Dart 2.17 introduced super parameters, a cleaner syntax that forwards parameters directly to the parent constructor:
class Student extends Person {
String school;
// super.name and super.age forward directly to Person's constructor
Student(super.name, super.age, this.school);
}When working with named constructors, you specify which parent constructor to call:
class Employee extends Person {
String department;
Employee(super.name, super.age, this.department);
Employee.intern(String name, this.department) : super(name, 18);
}The key rule is simple: the parent must be fully initialized before the child adds its own properties. Whether you use the traditional super() call or the newer super parameters, Dart ensures the inheritance chain is properly constructed from parent to child.
Challenge
EasyLet's build a product inventory system that demonstrates how constructors work with inheritance. You'll create a hierarchy where different product types extend a base product class, each requiring proper initialization through parent constructors.
You'll organize your code into two files:
product.dart: Define your product hierarchy here:- A
Productclass withString nameanddouble priceproperties, a constructor that takes both values, and a methodinfo()that prints[name]: $[price] - A
Bookclass that extendsProductand adds aString authorproperty. Use super parameters to forwardnameandpriceto the parent constructor - A
Electronicsclass that extendsProductand adds anint warrantyproperty (in months). Use the traditionalsuper()call in the initializer list to pass values to the parent
- A
main.dart: Import your product file and demonstrate both constructor inheritance approaches:- Create a
Bookwith name'Dart Essentials', price29.99, and author'Jane Smith' - Call its
info()method, then printAuthor: [author] - Print an empty line
- Create an
Electronicswith name'Wireless Mouse', price45.50, and warranty24 - Call its
info()method, then printWarranty: [warranty] months
- Create a
Both child classes inherit the info() method from Product without needing to override it. The key difference is in how they call the parent constructor - Book uses the cleaner super parameters syntax, while Electronics uses the traditional approach with super() in the initializer list.
Expected output:
Dart Essentials: $29.99
Author: Jane Smith
Wireless Mouse: $45.5
Warranty: 24 monthsCheat sheet
When a child class extends a parent, the parent's constructor must be called to properly initialize inherited fields.
Traditional approach - explicitly call parent constructor in initializer list:
class Person {
String name;
int age;
Person(this.name, this.age);
}
class Student extends Person {
String school;
Student(String name, int age, this.school) : super(name, age);
}Super parameters (Dart 2.17+) - forward parameters directly to parent constructor:
class Student extends Person {
String school;
Student(super.name, super.age, this.school);
}Named constructors - specify which parent constructor to call:
class Employee extends Person {
String department;
Employee(super.name, super.age, this.department);
Employee.intern(String name, this.department) : super(name, 18);
}Try it yourself
import 'product.dart';
void main() {
// TODO: Create a Book with:
// - name: 'Dart Essentials'
// - price: 29.99
// - author: 'Jane Smith'
// TODO: Call the book's info() method
// TODO: Print "Author: [author]"
// TODO: Print an empty line
// TODO: Create an Electronics with:
// - name: 'Wireless Mouse'
// - price: 45.50
// - warranty: 24
// TODO: Call the electronics' info() method
// TODO: Print "Warranty: [warranty] months"
}
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