The class methods, getter
and setter
, are used to manipulate the data of the class attributes. A setter is used to set the data of the fieldName
class to some variable, whereas a getter is used to read or get the data of the fieldName
class.
Setter
methodThe setter
method is used to set the data of a variable returned by the getter method. A default setter
function exists in all classes, although it can be overridden explicitly.
The set
keyword can be used to define the setter
method.
Syntax:
returnType set fieldName {
// set the value
}
Getter
methodA getter
method is used to get and save a specific fieldName
class in a variable. A default getter
method exists in all classes, but it can be overridden explicitly.
The get
keyword can be used to define the getter
method.
Syntax:
returnType get fieldName {
// return the value
}
Below is a code sample for the setter
and getter
method.
// implementing getter and setter method// Creating classclass Educative {// Creating a fieldString shotTitle;// Using the getter method to get inputString get shot_title {return shotTitle;}// Using the setter method to set the inputset shot_title (String title) {this.shotTitle = title;}}void main(){// Creating Instance of a classEducative edu = new Educative();// using class instance to access the class getter method// getter method to get the nameedu.shot_title = "Dart - Setter and Getter methods";// Print the inputprint("This is an Educative shot on ${edu.shot_title}");}