Classes are a common structure in many programming languages. They are used to arrange code into logically related groupings. In object oriented programming the idea is that each class represents a thing. This thing may be a real world object like a Book or a thing which operates on a book like a BookSorter. Much like the other languages at which weâ€™ve looked Dart has support for classes and also for fullÂ inheritance.
Here you can see Book has aÂ descendantÂ class TextBook which adds the additional edition field. Just like CoffeeScript and TypeScript there isÂ syntacticÂ sugar to allow for setting of public properties from the constructor. In this case the â€œthisâ€ keyword us used to denote what should be set. Interestingly on line 18 we have access to the edition information even though the instance was created as a Book and not a TextBook. This would not be possible with a language like C# or Java.
Dart has anÂ interestingÂ feature which is a built in factory method. Factories can be used to construct objects in a non-initialized way. Basically it is a way of overriding construction. Honestly it is a useful pattern but it isnâ€™t one which I use so frequently that I feel the need to have my language support it. But perhaps youâ€™re different.
In this example I retrieve the book from HTML5 local storage instead of creating a new book.