Pelajaran 21
Getter, setter, dan method
Instance method, getter/setter, static, operator override.
Pahami konsepnya
Getter: int get total => poin * 10; dipanggil tanpa kurung. Setter: set poinBaru(int v) => poin = v;. Static method milik class: static int hitung = 0;. Operator override: bool operator ==(Object lain) => nama == (lain as Siswa).nama;
Coba contoh kode
class Suhu {
double _celsius = 0;
double get celsius => _celsius;
set celsius(double v) => _celsius = v;
double get fahrenheit => _celsius * 9 / 5 + 32;
set fahrenheit(double f) => _celsius = (f - 32) * 5 / 9;
}
void main() {
var s = Suhu();
s.celsius = 25;
print(s.fahrenheit); // 77
}Getter fahrenheit MENGHITUNG dari _celsius — tidak menyimpan nilai sendiri. Setter menerima nilai lalu mengubah _celsius.
Latihan singkat
Uji: getter status → poin >= 70 harus `lulus`.