Basic Inheritance
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 36 of 110.
Inheritance allows a class to acquire the properties and methods of another class. Instead of rewriting the same code, you create a new class that builds upon an existing one. The original class is called the parent (or superclass), and the new class is the child (or subclass).
In Dart, you use the extends keyword to inherit from a parent class:
class Animal {
String name;
Animal(this.name);
void eat() {
print('$name is eating');
}
}
class Dog extends Animal {
Dog(String name) : super(name);
void bark() {
print('$name says woof!');
}
}
void main() {
var dog = Dog('Buddy');
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog
}The Dog class automatically has access to the name property and eat() method from Animal, plus its own bark() method. This creates an "is-a" relationship - a Dog is an Animal.
The child class can add new properties and methods, but it inherits everything public from the parent. Note that private members (those with _) are not directly accessible in subclasses from different libraries, though they still exist in the inherited object.
Challenge
EasyLet's build a vehicle system that demonstrates how inheritance allows child classes to reuse and extend parent class functionality. You'll create a parent class for general vehicles and a child class for a specific type of vehicle.
You'll organize your code into two files:
vehicle.dart: Define your classes here:- A
Vehicleclass (the parent) with aString brandproperty, a constructor that takes the brand, and a methodstart()that prints[brand] engine starting... - A
Motorcycleclass that extendsVehicle. It should have an additionalint ccproperty (engine displacement), a constructor that takes both the brand and cc (passing the brand to the parent usingsuper), and its own methodwheelie()that prints[brand] is doing a wheelie!
- A
main.dart: Import your vehicle file and demonstrate inheritance in action:- Create a
Vehiclewith brand'Toyota' - Call its
start()method - Create a
Motorcyclewith brand'Harley'and cc1200 - Call the motorcycle's
start()method (inherited from Vehicle) - Call the motorcycle's
wheelie()method (defined in Motorcycle) - Print
Motorcycle engine: [cc]ccto show the child's own property
- Create a
Notice how the Motorcycle class automatically gains access to the brand property and start() method from Vehicle, while also having its own unique cc property and wheelie() method. This is the power of inheritance - building upon existing code.
Expected output:
Toyota engine starting...
Harley engine starting...
Harley is doing a wheelie!
Motorcycle engine: 1200ccCheat sheet
Use the extends keyword to create a child class that inherits from a parent class:
class Animal {
String name;
Animal(this.name);
void eat() {
print('$name is eating');
}
}
class Dog extends Animal {
Dog(String name) : super(name);
void bark() {
print('$name says woof!');
}
}The child class inherits all public properties and methods from the parent class. Use super in the child constructor to pass parameters to the parent constructor.
Child classes can add their own properties and methods while still accessing inherited ones:
var dog = Dog('Buddy');
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in DogThis creates an "is-a" relationship - a Dog is an Animal.
Try it yourself
import 'vehicle.dart';
void main() {
// TODO: Create a Vehicle with brand 'Toyota'
// TODO: Call the vehicle's start() method
// TODO: Create a Motorcycle with brand 'Harley' and cc 1200
// TODO: Call the motorcycle's start() method (inherited from Vehicle)
// TODO: Call the motorcycle's wheelie() method
// TODO: Print 'Motorcycle engine: [cc]cc' using the motorcycle's cc property
}
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