Dart classes are declared by using the class keyword, followed by the class name, ancestor classes, and implemented interfaces. Then, the class body is enclosed by a pair of curly braces, where you can add class members, that include the following:
- Fields: These are variables used to define the data an object can hold.
- Accessors: Getters and setters, as the name suggests, are used to access the fields of a class, where get is used to retrieve a value, and the set accessor is used to modify the corresponding value.
- Constructor: This is the creator method of a class where the object instance fields are initialized.
- Methods: The behavior of an object is defined by the actions it can take. These are the object functions.
Refer to the following small class definition example:
class Person {
String firstName;
String lastName;
String getFullName() => "$firstName $lastName";
}
main() {
Person somePerson = new Person();
somePerson.firstName = "Clark";
somePerson.lastName = "Kent";
print(somePerson.getFullName()); // prints Clark Kent
}
Now, let's take a look at the Person class declared in the preceding code and make some observations:
- To instantiate a class, we use the new (optional) keyword followed by the constructor invocation. As we advance in this book, you will notice that this keyword is used less.
- It does not have an ancestor class explicitly declared, but it does have one, the object type, as already mentioned, and this inheritance happens implicitly in Dart.
- It has two fields, firstName and lastName, and a method, getFullName(), which concatenates both by using string interpolation and then returns.
- It does not have any get or set accessor declared, so how did we access firstName and lastName to mutate it? A default get/set accessor is defined for every field in a class.
- The dot class.member notation is used to access a class member, whatever it is—a method or a field (get/set).
- We have not defined a constructor for the class, but, as you may be thinking, there's a default empty constructor (no arguments) already provided for us.