Dart Getters and Setters
Getters and setters are the special class method that is used to read and write access to an object's properties. The getter method is used to reads the value of the variable or retrieve the value and setter method is used to set or initialize respective class fields. By default, all classes are associated with getter and setter method. However, we can override the default methods by defining getter and setter method explicitly.
Defining a getter
We can define the getters method by using the get keyword with no parameter a valid return type.
Syntax:
- return_type get field_name{
- }
Defining a setter
We can declare the setter method using the set keyword with one parameter and without return type.
Syntax:
Example:
- class Student {
- String stdName;
- String branch;
- int stdAge;
-
- String get std_name
- {
- return stdName;
- }
- void set std_name(String name)
- {
- this.stdName = name;
-
- }
- void set std_age(int age) {
- if(age> = 20){
- print("Student age should be greater than 20")
- }else{
- this.stdAge = age;
- }
- }
-
- }
- int get std_age{
- return stdAge;
-
- }
- void set std_branch(String branch_name) {
- this.branch = branch_name;
-
- }
- int get std_branch{
- return branch;
- }
-
- }
- void main(){
- Student std = new Student();
- std.std_name = 'John';
- std.std_age = 24;
- std.std_branch = 'Computer Science';
-
- print("Student name is: ${std_name}");
- print("Student age is: ${std_age}");
- print("Student branch is: ${std_branch}");
- }
Output
Student name is: John
Student age is: 24
Student Branch is: Computer Science
We can also place the getter and setter method just after the. Now, let's understand the following example:
Example - 2
- class Car {
- String makedate;
- String modelname;
- int manufactureYear;
- int carAge;
- String color;
-
- int get age {
- return carAge;
- }
-
- void set age(int currentYear) {
- carAge = currentYear - manufactureYear;
- }
-
- Car({this.makedate,this.modelname,this.manufactureYear,this.color,});
- }
-
- void main() {
- Car c =
- Car(makedate:"Renault 20/03/2010",modelname:"Duster",manufactureYear:2010,color:"White");
- print("The car company is: ${c.makedate}");
- print("The modelname is: ${c.modelname}");
- print("The color is:${c.color}");
- c.age = 2020;
- print(c.age);
- }
Output
The car company is: Honda 20/03/2010
The modelname is: City
The color is: White
10
Explanation:
In the above code, we defined the getter and setter methods before the constructor
Comments
Post a Comment