Chapter 7. Extending classes and interfaces
This chapter covers
- Building class and interface inheritance hierarchies
- Introducing the Object base class
- Understanding the dynamic type annotation
Object-oriented programming allows for more than just encapsulating data and behavior in a class. It allows you to extend existing behavior defined elsewhere, which promotes great code reuse. Reusing existing code lets you write less new code in your apps and has the added benefit that existing code should also be tested code.
In this chapter, we’ll examine class and interface inheritance in Dart, including how to provide new functionality by overriding existing methods and properties and how to write abstract classes that you can use only as parents in an inheritance hierarchy. If you have written in Java or C#, this will be familiar. But those from a JavaScript background should note the absence of JavaScript’s prototypical inheritance mechanism.
We’ll explore the base Object class from which all other classes and types inherit, including strings, numbers, Boolean values, null, and your own custom classes. Object provides some standard methods and properties that you can override in your own classes, such as the toString() method. We’ll also look at the dynamic type, which Dart uses to enable optional typing.