問題一覧に戻る
中級オブジェクト指向
問題57: カプセル化
カプセル化はデータを隠蔽し、公開メソッドを通じてのみアクセスを許可する設計原則です。privateフィールドとpublicメソッドを組み合わせて実現します。
public class Account {
// // カプセル化
double balance;
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
// // 公開インターフェース
double getBalance() {
return balance;
}
public static void main(String[] args) {
Account acc = new Account();
acc.deposit(100);
System.out.println("Balance: " + acc.getBalance());
}
}