Extension vs subclass
- Dart course
- Expert
- Lesson 23/47
- 5 min
Learn the difference between extension and subclass.
Extension vs subclass
Extension and subclass are two ways to add functionality to a type. An extension adds methods from outside (no inheritance); a subclass extends the type (with inheritance).
Extension advantages: can extend final classes, add functionality to types you don't own. Subclass advantages: can add state, override methods, provide polymorphism. Which to use depends on the need.
When to use which?
Use an extension: when you only want to add helper methods, when you don't own the type, when inheritance isn't needed. Use a subclass: when you want to add new state (fields), when you'll override, when polymorphism is required.
Extensions are stateless; you cannot add new fields. Subclasses can add state. Also, extensions are resolved statically; subclasses are dynamic. So when polymorphism is needed, a subclass is required.
Practice A StringShout extension
Define a StringShout extension on String with a String shout() => toUpperCase() + '!'; method. In main add print('hello'.shout());.
Starter code
void main() {
// define a StringShout extension (on String; shout method)
// print 'hello'.shout()
}Sample solution
extension StringShout on String {
String shout() => toUpperCase() + '!';
}
void main() {
print('hello'.shout());
}Expected output
HELLO!
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Extension on String
extension StringShout on ____ {
String shout() => toUpperCase() + '!';
}
extension StringShout on String {
String shout() => toUpperCase() + '!';
}
Explanation: extension StringShout on String extends String.
2 Match extension vs subclass differences
| Term | Meaning |
|---|---|
Extension |
No inheritance |
Subclass |
With inheritance |
Final class |
Extendable via extension |
Polymorphism |
With subclass |
3 When is an extension used instead of a subclass?
- To override methods
- To add new fields to a type
- For polymorphism
- To only add helper methods to a type Correct answer
Explanation: an extension is ideal for adding helper methods.