The structure of a class
java
public class ClassName {
// 1. Instance variables (fields) — the DATA
private type variableName;
// 2. Constructors — INITIALIZATION
public ClassName(parameters) {
// assign values to instance variables
}
// 3. Methods — BEHAVIOR
public returnType methodName(parameters) {
// code that uses instance variables
}
}
A complete example: BankAccount
java
public class BankAccount {
// Instance variables — each BankAccount object has its own copy
private String owner;
private double balance;
// Constructor — called when you create a new BankAccount
public BankAccount(String owner, double initialBalance) {
this.owner = owner;
this.balance = initialBalance;
}
// Accessor (getter) — returns data without changing it
public double getBalance() {
return balance;
}
public String getOwner() {
return owner;
}
// Mutator (setter) — changes the object's data
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
}
}
// toString — provides a String representation
public String toString() {
return owner + ": $" + balance;
}
}
Using the class
java
BankAccount acct = new BankAccount("Alice", 1000.0);
acct.deposit(500.0);
acct.withdraw(200.0);
System.out.println(acct.getBalance()); // 1300.0
System.out.println(acct); // Alice: $1300.0
Instance variables
java
public class Circle {
private double radius; // each Circle has its own radius
private String color; // each Circle has its own color
}
Access modifiers
java
public class Student {
private String name; // only Student methods can access
public int id; // anyone can access (BAD practice!)
}
Student s = new Student();
// s.name = "Alice"; // COMPILE ERROR — name is private
s.id = 42; // works — id is public (but you shouldn't do this)
Why private?
java
// Without private — anyone can break your object:
public class BankAccount {
public double balance; // BAD!
}
BankAccount acct = new BankAccount();
acct.balance = -1000000; // No validation! Negative balance!
// With private — you control access:
public class BankAccount {
private double balance; // GOOD!
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount; // validated!
}
}
}
Multiple objects = independent data
java
BankAccount a = new BankAccount("Alice", 1000);
BankAccount b = new BankAccount("Bob", 500);
a.deposit(200);
// a.balance = 1200
// b.balance = 500 — unchanged!
AP Exam Tips
- •
- •
- •
- •
- •
Common Mistakes
- •
- •
- •
- •