Accessing Instance Fields
- The deposit method of the BankAccount class
can access
the private instance field:
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
- Other methods cannot:
public class BankRobber
{
public static void main(String[] args)
{
BankAccount momsSavings = new BankAccount(1000);
. . .
momsSavings.balance = -1000; // ERROR
}
}
- Encapsulation = Hiding data and providing access through methods