![]() |
VOOZH | about |
Getters and Setters, also called accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively.
A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value.
Defining a Getter
ReturnType get identifier {
// statements
}
Defining a Setter
set identifier(Type value) {
// statements
}
Example :
The following example shows how you can use getters and setters in a Dart class:
Output:
Age should be greater than 5
GFG
0
Example :
Output:
Is cat hungry? true
Is cat cuddly? false
Feed cat.
Is cat hungry? false
Is cat cuddly? true