Encapsulation: private fields, getters, setters · Enkapsulasi: bidang privat, getter, setter
Protect your data
- Encapsulation means hiding an object's data and only changing it through methods.
- This keeps the data safe. Other code cannot put a bad value into it.
- The main tools are the words
privateandpublic.
Lindungi data Anda
- Enkapsulasi berarti menyembunyikan data objek dan hanya mengubahnya melalui metode.
- Hal ini menjaga keamanan data. Kode lain tidak dapat memasukkan nilai buruk ke dalamnya.
- Alat utamanya adalah kata-kata
privatedanpublic.
private fields
- Mark instance variables
privateso code outside the class cannot touch them directly. - Methods inside the same class can still use them.
- This is the normal style for AP CSA: fields are
private.
Field private
- Tandai variabel instance sebagai
privateagar kode di luar kelas tidak dapat menyentuhnya secara langsung. - Metode di dalam kelas yang sama masih dapat menggunakannya.
- Ini adalah gaya standar untuk AP CSA: field adalah
private.
public class BankAccount {
private double balance; // hidden from outside code
public BankAccount(double start) {
this.balance = start;
}
}
Accessors (getters)
- A field is private, so we add a
publicmethod to read it. - A method that returns a field is called an accessor or getter.
- It usually starts with
get, likegetBalance().
Akses (getter)
- Karena field bersifat pribadi, kita menambahkan metode
publicuntuk membacanya. - Metode yang mengembalikan nilai field disebut aksesor atau getter.
- Biasanya dimulai dengan
get, sepertigetBalance().
public class BankAccount {
private double balance;
public BankAccount(double start) {
this.balance = start;
}
public double getBalance() {
return this.balance;
}
}
Mutators (setters)
- A method that changes a field is called a mutator or setter.
- It can check the new value first and refuse a bad one.
- Below,
depositignores a negative amount, so the balance stays safe.
Mutator (setter)
- Metode yang mengubah field disebut mutator atau setter.
- Metode ini dapat memeriksa nilai baru terlebih dahulu dan menolak nilai yang buruk.
- Di bawah ini,
depositmengabaikan jumlah negatif, sehingga saldo tetap aman.
public class BankAccount {
private double balance;
public BankAccount(double start) {
this.balance = start;
}
public void deposit(double amount) {
if (amount > 0) {
this.balance = this.balance + amount;
}
}
public double getBalance() {
return this.balance;
}
}
static vs instance
- An instance field belongs to one object. Each object has its own.
- A
staticfield belongs to the class itself — it is shared by all objects. - Below,
countrises by 1 every time anyRobotis built.
static vs instance
- Field instance milik satu objek. Setiap objek memilikinya sendiri.
- Field
staticmilik kelas itu sendiri — ia dibagikan oleh semua objek. - Di bawah ini,
countnaik sebanyak 1 setiap kali apa punRobotdibuat.
public class Robot {
private static int count = 0; // shared by all robots
public Robot() {
count = count + 1;
}
public static int getCount() {
return count;
}
}
toString()
toString()returns text that describes the object.- Java calls it automatically when you print the object or join it with
+. - It takes no parameters and returns a
String.
toString()
toString()mengembalikan teks yang mendeskripsikan objek.- Java memanggilnya secara otomatis saat Anda mencetak objek atau menggabungkannya dengan
+. - Tidak menerima parameter dan mengembalikan
String.
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "(" + this.x + ", " + this.y + ")";
}
}
Common mistakes
- Make fields
privateand reach them through getters and setters. - A setter can check a value before storing it.
Kesalahan umum
- Buat field menjadi
privatedan akses melalui getter dan setter. - Setter dapat memeriksa nilai sebelum menyimpannya.
Now you try
- Fill in each class so its private data is changed only through safe methods.
- A hidden Harness builds the object, calls the methods, and checks the results.
- Press Run to compile, then Check answer.
Sekarang Anda coba
- Isilah setiap kelas agar data pribadinya diubah hanya melalui metode yang aman.
- Harness tersembunyi membangun objek, memanggil metode, dan memeriksa hasilnya.
- Tekan Run untuk mengkompilasi, lalu Check answer.
Complete BankAccount. Keep balance private. deposit(amount) adds the amount only if it is greater than 0. withdraw(amount) subtracts only if the amount is greater than 0 and not more than the balance (no overdraft). getBalance() returns the balance. · Lengkapi BankAccount. Jaga balance tetap privat. deposit(amount) menambahkan jumlah hanya jika lebih besar dari 0. withdraw(amount) mengurangi hanya jika jumlahnya lebih besar dari 0 dan tidak melebihi saldo (tidak ada overdraft). getBalance() mengembalikan saldo.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Complete Temperature. The constructor stores an int degrees in a private field. toString() returns the degrees followed by C — for 21 it returns 21C. · Lengkapi Temperature. Konstruktor menyimpan sebuah int degrees di bidang privat. toString() mengembalikan derajat diikuti oleh C — untuk 21 ia mengembalikan 21C.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Complete Widget. A private static field count starts at 0. Every time a Widget is built, the constructor adds 1 to count. The static method getCount() returns how many widgets have been built. · Lengkapi Widget. Bidang static privat count dimulai dari 0. Setiap kali sebuah Widget dibuat, konstruktor menambahkan 1 ke count. Metode static getCount() mengembalikan berapa banyak widget yang telah dibuat.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.