We will look at how we can create classes and explore some various features. Dart adopts a single-inheritance model, meaning that you can only extend a single class. We will therefore extend our class example by creating an Employee subclass of a parent Person class.
Instructor: [00:00] Classes allow you to define a blueprint that represents a particular object. In this example, we are creating a blueprint describing a person. Creating classes has similar syntax to other languages, and this is by design.
[00:18] In the person constructor, we accept the name and age parameter, assigning its values to our instance properties, name and age. There is a simpler form of assigning these values with shorthand constructors.
[00:29] We can also be specific about our instance property types. You can declare private instance properties or methods by prefixing them with an underscore. We can also define getters and setters for our name, private property.
[00:56] Languages like Java allow you to specify multiple constructors for a class, differentiated by the amount of parameters defined for each constructor. In Dart, however, we can use named constructors without worrying about the parameter count.
[01:16] Parameters can also be optional for the constructor and its methods. Alternatively, use the optional positional parameter. We can override several operators to perform various tasks like arithmetic and comparisons. In this example, we will override the equal operator.
[01:50] Let's create a matching Jane object, and compare. Classes are extendable using the extends keyword. To demonstrate this, we will create an employee class extending person. This will inherit instance variables and methods from person.
[02:09] In this constructor, we will pass the name and age variables to the parent person constructor using the super method. We can also override the methods from the parent class. Fields that won't be changed once they are set can be marked as final.
[02:36] Attempting to change a field marked as final will return an error. A feature supported with instantiating classes are method cascades. These allow to adopt a chaining pattern with invoking methods and setting values. Instead of doing this, you could instead use the cascade operator.
[03:01] Let's run this again.