Abstract Methods
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 44 of 110.
An abstract method is a method declared inside an abstract class that has no body. It defines the method signature but leaves the implementation to each subclass. Any class that extends the abstract class must override all abstract methods, or it will also be abstract.
abstract class Animal {
// Abstract method - no body, must be implemented by subclasses
String makeSound();
// Concrete method - has a body, shared by all subclasses
void breathe() {
print('Breathing...');
}
}
class Dog extends Animal {
@override
String makeSound() {
return 'Woof!'; // Must provide implementation
}
}
class Cat extends Animal {
@override
String makeSound() {
return 'Meow!'; // Different implementation, same signature
}
}If a subclass forgets to implement an abstract method, Dart will give you a compile error. This is the whole point - abstract methods enforce a contract. Every subclass is guaranteed to have that method, so you can safely call it on any instance of the abstract type.
// You can use the abstract type as a variable type
Animal a = Dog();
print(a.makeSound()); // Woof!
Animal b = Cat();
print(b.makeSound()); // Meow!Abstract methods are different from concrete methods in an abstract class. Concrete methods have a body and are inherited as-is. Abstract methods have no body and must be overridden.
You can mix both in the same abstract class to share some behavior while forcing subclasses to define their own for others.
| Feature | Abstract Method | Concrete Method |
|---|---|---|
| Has body | No | Yes |
| Must override | Yes | No |
| Purpose | Enforce contract | Share behavior |
| Where | Abstract class only | Any class |
Challenge
EasyLet's build a shape calculator that demonstrates abstract methods in action. You'll define an abstract class with abstract methods that each shape must implement differently, then use those shapes through a common interface.
You'll organize your code into four files:
shape.dart: Define an abstract classShapewith afinalfieldcolor(String) and a constructor that initializes it. Declare two abstract methods:double area()anddouble perimeter(). Also add a concrete methoddescribe()that printsA [color] shape with area: [area] and perimeter: [perimeter]. Becausearea()andperimeter()are abstract, each subclass will provide its own calculation, butdescribe()works for all of them without being overridden.circle.dart: Create aCircleclass that extendsShape. It has afinalfieldradius(double). Its constructor takescolorandradiusand passescolortosuper. Implementarea()to return3.14 * radius * radiusandperimeter()to return2 * 3.14 * radius.rectangle.dart: Create aRectangleclass that extendsShape. It hasfinalfieldswidthandheight(both double). Its constructor takescolor,width, andheightand passescolortosuper. Implementarea()to returnwidth * heightandperimeter()to return2 * (width + height).main.dart: Import all files. Create aCirclewith color'red'and radius5.0, and aRectanglewith color'blue', width4.0, and height6.0. Calldescribe()on each shape. Then create aList<Shape>containing both shapes, loop through the list, and printArea: [area]for each shape.
Expected output:
A red shape with area: 78.5 and perimeter: 31.400000000000002
A blue shape with area: 24.0 and perimeter: 20.0
Area: 78.5
Area: 24.0Cheat sheet
An abstract method is a method declared in an abstract class without a body. Subclasses must override it to provide their own implementation.
abstract class Animal {
// Abstract method - no body
String makeSound();
// Concrete method - has a body
void breathe() {
print('Breathing...');
}
}Subclasses must implement all abstract methods:
class Dog extends Animal {
@override
String makeSound() {
return 'Woof!';
}
}
class Cat extends Animal {
@override
String makeSound() {
return 'Meow!';
}
}You can use the abstract type as a variable type:
Animal a = Dog();
print(a.makeSound()); // Woof!
Animal b = Cat();
print(b.makeSound()); // Meow!| Feature | Abstract Method | Concrete Method |
|---|---|---|
| Has body | No | Yes |
| Must override | Yes | No |
| Purpose | Enforce contract | Share behavior |
| Where | Abstract class only | Any class |
Try it yourself
import 'shape.dart';
import 'circle.dart';
import 'rectangle.dart';
void main() {
// TODO: Create a Circle with color 'red' and radius 5.0
// TODO: Create a Rectangle with color 'blue', width 4.0, and height 6.0
// TODO: Call describe() on the circle
// TODO: Call describe() on the rectangle
// TODO: Create a List<Shape> containing both shapes
// TODO: Loop through the list and print "Area: [area]" for each shape
}
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