ACSA Exam Prep
Unit 3 · Class Creation · Topic 3.3

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.

Learning objectives
  • 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.

Code
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());
Output
75.5
10.0

Access rules for this course

MemberUse
Class headerpublic class Name
Instance variablesprivate (encapsulation)
Constructorspublic
Methodspublic if other classes call them; private for internal helpers
Key points
  • 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 are private.
  • Each object has its own copy of every instance variable.
Watch out
  • On the Class Design FRQ, public instance variables cost a point.
Quick check
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.