8. วัตถุสิ่งของ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 8-12  ตัวอย่างการใช้ private เพื่อปกปิดการเข้าใช้ตัวแปรจากภายนอก
public class BankAccount {
  private String id;    // หมายเลขบัญชี;
  private double balance; // ยอดเงินคงเหลือ;

  public BankAccount(String newID) {
    id = newID;
  }
  public String getID() {
    return id;
  }
  public double getBalance() {
    return balance;
  }
  public void deposit(double amt) {
    if (amt < 0) throw new IllegalArgumentException("amt<0:"+amt);
    balance += amt;
  }
  public void withdraw(double amt) {
    if (amt < 0) throw new IllegalArgumentException("amt<0:"+amt);
    if (amt > balance) throw new IllegalArgumentException("ไม่พอ");
    balance -= amt;
  }
  public void transferTo(BankAccount to, double amt) {
    withdraw(amt);
    to.deposit(amt);
  }
}
©2009 S.Prasitjutrakul