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
- Instance variables are
private; they store each object's state.
- Constructors have the class name and no return type; they initialize instance variables.
- Accessor (getter) methods return values; mutator (setter) methods change them.
- this refers to the current object. static variables and methods belong to the class, not to individual objects.
- Scope: local variables exist only inside their block.
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?
- So they run faster
- To protect an object's data so it can only be changed through its methods (encapsulation)
- Because Java requires it
- So they can be static
Show answer
Answer: B. Encapsulation keeps data safe from outside code and lets the class control how it changes.