Anatomy of a Class
Skill 1.ASkill 2.B
Big idea: A class has three parts: instance variables (the data), constructors (setup), and methods (behavior). private hides the data so only the class's own methods can touch it.
- Develop code to designate access and visibility constraints to classes, data, constructors, and methods.
The parts of a class
public class BankAccount {
private String owner; // instance variables:
private double balance; // each object has its own
public BankAccount(String name, double start) {
owner = name;
balance = start;
}
public double getBalance() { // accessor
return balance;
}
public void deposit(double amount) { // mutator
balance += amount;
}
}Using the class
Other classes create objects and call public methods. They can't touch private data directly; acct.balance from outside the class won't compile.
BankAccount acct = new BankAccount("Lee", 50.0);
acct.deposit(25.5);
System.out.println(acct.getBalance());
BankAccount other = new BankAccount("Kim", 10.0);
System.out.println(other.getBalance());Output75.5 10.0
Access rules for this course
| Member | Use |
|---|---|
| Class header | public class Name |
| Instance variables | private (encapsulation) |
| Constructors | public |
| Methods | public if other classes call them; private for internal helpers |
- Encapsulation hides implementation details from other classes.
private: only the declaring class can access it.public: any class can.- Classes and constructors are
public; instance variables areprivate. - Each object has its own copy of every instance variable.
- On the Class Design FRQ, public instance variables cost a point.
In client code, why does acct.balance = 1000; fail?
Show answer
balance is private, so it can only be accessed inside BankAccount. It's a compile-time error.