StudyFox

Writing classes

Open in StudyFox Free, no ads. Practice, track progress and quiz yourself in the app.

AP Computer Science A · Lesson 4 of 6 · 9 min read

public class BankAccount {
    private double balance;

    public BankAccount(double start) {
        balance = start;
    }

    public void deposit(double amt) {
        if (amt > 0) {
            balance += amt;
        }
    }

    public double getBalance() {
        return balance;
    }
}

Check your understanding

Why are instance variables usually declared private?

  1. So they run faster
  2. To protect an object's data so it can only be changed through its methods (encapsulation)
  3. Because Java requires it
  4. So they can be static
Show answer

Answer: B. Encapsulation keeps data safe from outside code and lets the class control how it changes.