-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path25. getter_setter.dart
242 lines (205 loc) · 7.77 KB
/
25. getter_setter.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/// Getters and Setters in Dart
///
/// Introduction:
///
/// In Dart, getters and setters are special methods that provide controlled access to an object's properties (fields).
/// They are a key part of encapsulation, allowing you to hide the internal representation of data and control how it's accessed and modified.
///
/// Getters:
///
/// * Purpose: Getters provide read-only access to an object's properties.
/// * Definition: They are defined using the `get` keyword followed by the property name.
/// * Usage: They are accessed like properties (without parentheses).
/// * Functionality:
/// - Retrieve the value of a field.
/// - Compute and return a value based on other fields or logic.
/// - Perform validation or other operations before returning a value.
/// * No Parameters: Getters do not take any parameters.
/// * Return Value: Getters must return a value.
///
/// Setters:
///
/// * Purpose: Setters allow controlled modification of an object's properties.
/// * Definition: They are defined using the `set` keyword followed by the property name.
/// * Usage: They are accessed like properties using the assignment operator (`=`).
/// * Functionality:
/// - Assign a new value to a field.
/// - Validate the new value before assigning it.
/// - Trigger side effects or other actions when a field is updated.
/// * Single Parameter: Setters always take exactly one parameter, which represents the new value.
/// * No Return Value: Setters do not return any value (they have a `void` return type).
///
/// Benefits of Using Getters and Setters:
///
/// 1. Encapsulation: They help hide the internal representation of data, making it easier to change the implementation without affecting the code that uses the class.
/// 2. Data Integrity: Setters can enforce rules and constraints on the values that can be assigned to a field, ensuring that the data remains in a valid state.
/// 3. Abstraction: They can hide complex logic for accessing or updating a field behind a simple interface.
/// 4. Code Maintainability: They make code more maintainable by centralizing the logic for accessing and modifying a field in one place.
/// 5. Flexibility: You can change the internal implementation of how a value is computed or set without changing how it's accessed.
///
/// Example 1: Basic Getter and Setter
///
/// This example demonstrates a simple getter and setter for a `radius` property of a `Circle` class.
class Circle {
double _radius = 0; // Private field
// Getter for radius
double get radius => _radius;
// Setter for radius
set radius(double newRadius) {
if (newRadius >= 0) {
_radius = newRadius;
} else {
print('Radius cannot be negative.');
}
}
}
///
/// Example 2: Computed Getter
///
/// This example demonstrates a getter that computes the area of a circle.
class Circle2 {
double _radius;
Circle2(this._radius);
// Getter for radius
double get radius => _radius;
// Computed getter for area
double get area => 3.14159 * _radius * _radius;
}
///
/// Example 3: Getter and Setter with Validation
///
/// This example demonstrates a getter and setter that validate the new value before assigning it.
class Person {
String _name;
int _age;
Person(this._name, this._age);
// Getter for age
int get age => _age;
// Setter for age with validation
set age(int newAge) {
if (newAge >= 0) {
_age = newAge;
} else {
print('Age cannot be negative.');
}
}
// Getter for name
String get name => _name;
// Setter for name with validation
set name(String newName) {
if (newName.isNotEmpty) {
_name = newName;
} else {
print('Name cannot be empty.');
}
}
}
/// Example 4: Getter and Setter in `BankAccount` Class
///
/// This example demonstrates a getter and setter in `BankAccount` class.
class BankAccount {
// Private fields (data hiding)
String _accountNumber;
double _balance;
// Constructor
BankAccount(this._accountNumber, this._balance);
// Getter for account number (read-only)
String get accountNumber => _accountNumber;
// Getter for balance (read-only)
double get balance => _balance;
// Setter for balance (controlled modification)
set deposit(double amount) {
if (amount > 0) {
_balance += amount;
print('Deposited $amount. New balance: $_balance');
} else {
print('Invalid deposit amount.');
}
}
set withdraw(double amount) {
if (amount > 0 && _balance >= amount) {
_balance -= amount;
print('Withdrew $amount. New balance: $_balance');
} else if (amount <= 0) {
print('Invalid withdrawal amount.');
} else {
print('Insufficient funds.');
}
}
// Method to display account information
void displayAccountInfo() {
print('Account Number: $_accountNumber, Balance: $_balance');
}
}
/// Example 5: Getter and Setter in `Dog` Class
///
/// This example demonstrates a getter and setter in `Dog` class.
class Dog {
String name;
String breed;
int age;
String? color;
// Constructor
Dog(this.name, this.breed, this.age, [this.color]);
// Named Constructor
Dog.puppy(this.name, this.breed, [this.color]) : age = 0;
// Methods
void bark() {
print('$name says Woof!');
}
void eat(String food) {
print('$name is eating $food.');
}
void describe() {
print('$name is a $age-year-old $breed.${color != null ? ' Its color is $color.' : ''}');
}
// Getter
String get dogInfo => 'Name: $name, Breed: $breed, Age: $age${color != null ? ', Color: $color' : ''}';
// Setter
set updateAge(int newAge) {
if (newAge >= 0) {
age = newAge;
} else {
print('Age cannot be negative.');
}
}
}
void main() {
// Example 1: Basic Getter and Setter
Circle circle1 = Circle();
circle1.radius = 5.0;
print('Circle radius: ${circle1.radius}'); // Output: Circle radius: 5.0
circle1.radius = -2.0; // Output: Radius cannot be negative.
print('Circle radius: ${circle1.radius}'); // Output: Circle radius: 5.0
// Example 2: Computed Getter
Circle2 circle2 = Circle2(3.0);
print('Circle radius: ${circle2.radius}'); // Output: Circle radius: 3.0
print('Circle area: ${circle2.area}'); // Output: Circle area: 28.27431
// Example 3: Getter and Setter with Validation
Person person1 = Person('John', 30);
person1.age = 35;
print('Person age: ${person1.age}'); // Output: Person age: 35
person1.age = -5; // Output: Age cannot be negative.
print('Person age: ${person1.age}'); // Output: Person age: 35
person1.name = ''; // Output: Name cannot be empty.
print('Person name: ${person1.name}'); // Output: Person name: John
person1.name = 'Usama';
print('Person name: ${person1.name}'); // Output: Person name: Usama
// Example 4: Getter and Setter in `BankAccount` Class
BankAccount account1 = BankAccount('123456789', 1000.0);
print('Account Number: ${account1.accountNumber}'); // Output: Account Number: 123456789
print('Balance: ${account1.balance}'); // Output: Balance: 1000.0
account1.deposit = 500.0; // Output: Deposited 500.0. New balance: 1500.0
account1.withdraw = 200.0; // Output: Withdrew 200.0. New balance: 1300.0
account1.withdraw = 1500.0; // Output: Insufficient funds.
account1.deposit = -100; // Output: Invalid deposit amount.
account1.withdraw = -100; // Output: Invalid withdrawal amount.
print('Balance: ${account1.balance}'); // Output: Balance: 1300.0
// Example 5: Getter and Setter in `Dog` Class
Dog dog1 = Dog('Buddy', 'Golden Retriever', 3, 'Golden');
print(dog1.dogInfo); // Output: Name: Buddy, Breed: Golden Retriever, Age: 3, Color: Golden
dog1.updateAge = 4;
print(dog1.dogInfo); // Output: Name: Buddy, Breed: Golden Retriever, Age: 4, Color: Golden
dog1.updateAge = -2; // Output: Age cannot be negative.
print(dog1.dogInfo); // Output: Name: Buddy, Breed: Golden Retriever, Age: 4, Color: Golden
}