The super Keyword
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 37 of 110.
The super keyword gives a child class direct access to its parent class. You've already seen it in constructors with super(name), but it's useful in other contexts too.
When you need to call the parent's constructor, super passes arguments up the inheritance chain:
class Vehicle {
String brand;
int year;
Vehicle(this.brand, this.year);
}
class Car extends Vehicle {
int doors;
Car(String brand, int year, this.doors) : super(brand, year);
}The super keyword also lets you access parent methods and properties from within the child class. This is especially useful when you want to use the parent's behavior alongside your own:
class Animal {
String name;
Animal(this.name);
void makeSound() {
print('$name makes a sound');
}
}
class Cat extends Animal {
Cat(String name) : super(name);
void makeSound() {
super.makeSound(); // Call parent's method first
print('$name says meow!');
}
}When you call super.makeSound(), you're explicitly invoking the parent's version of the method. Without super, calling makeSound() would refer to the current class's method, potentially causing infinite recursion.
Think of super as saying "use my parent's version" - whether that's a constructor, method, or property.
Challenge
EasyLet's build a messaging system that demonstrates how the super keyword lets child classes access and extend their parent's behavior. You'll create a hierarchy where different message types build upon a base message class.
You'll organize your code into two files:
message.dart: Define your message classes here:- A
Messageclass (the parent) with aString senderandString content. Include a constructor that takes both values and a methoddisplay()that printsFrom [sender]: [content] - An
UrgentMessageclass that extendsMessage. It should have an additionalString priorityproperty. The constructor takes sender, content, and priority, passing the first two to the parent usingsuper. Override thedisplay()method to first call the parent's version usingsuper.display(), then printPriority: [priority]on the next line
- A
main.dart: Import your message file and demonstrate howsuperworks in both constructors and methods:- Create a regular
Messagefrom'Alice'with content'Hello there!' - Call its
display()method - Print an empty line for separation
- Create an
UrgentMessagefrom'Bob'with content'Server is down!'and priority'HIGH' - Call its
display()method
- Create a regular
Notice how UrgentMessage uses super in two ways: in the constructor to pass data to the parent, and in the overridden method to include the parent's output before adding its own.
Expected output:
From Alice: Hello there!
From Bob: Server is down!
Priority: HIGHCheat sheet
The super keyword provides access to a parent class from within a child class.
Use super() in a child class constructor to pass arguments to the parent constructor:
class Vehicle {
String brand;
int year;
Vehicle(this.brand, this.year);
}
class Car extends Vehicle {
int doors;
Car(String brand, int year, this.doors) : super(brand, year);
}Use super to call parent methods from within overridden methods:
class Animal {
String name;
Animal(this.name);
void makeSound() {
print('$name makes a sound');
}
}
class Cat extends Animal {
Cat(String name) : super(name);
void makeSound() {
super.makeSound(); // Call parent's method first
print('$name says meow!');
}
}Without super, calling a method name directly refers to the current class's version, which can cause infinite recursion in overridden methods.
Try it yourself
import 'message.dart';
void main() {
// TODO: Create a regular Message from 'Alice' with content 'Hello there!'
// TODO: Call the display() method on the message
// TODO: Print an empty line for separation
// TODO: Create an UrgentMessage from 'Bob' with content 'Server is down!' and priority 'HIGH'
// TODO: Call the display() method on the urgent message
}
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