1. 객체지향(OOP) 기본 개념
1.1 객체, 클래스, 인스턴스
- 클래스(class): 설계도. 어떤 데이터(필드)와 동작(메서드)을 가진 “타입”을 정의한다.
- 객체(object): 설계도를 바탕으로 실제로 메모리에 만들어진 실체. 설계도에 의해 만들어진 객체는 항상 ‘상태’ 와 ‘행동’을 갖는다.
- 인스턴스(instance): “특정 클래스의 객체”라는 의미를 강조할 때 쓰는 표현.
객체 == 해당 클래스의 인스턴스. 같은 클래스로부터 만들어진 인스턴스들의 ‘상태’ 는 서로 다르다.
class BankAccount {
private String owner;
private long balance;
public BankAccount(String owner, long init) {
this.owner = owner;
this.balance = init;
}
public void deposit(long amount) { balance += amount; }
public boolean withdraw(long amount) {
if (balance < amount) return false;
balance -= amount; return true;
}
public long getBalance() { return balance; }
}
public class Main {
public static void main(String[] args) {
BankAccount a = new BankAccount("Kim", 1000);
BankAccount b = new BankAccount("Lee", 1000);
a.deposit(500); // a: 1500
b.withdraw(300); // b: 700
System.out.println(a.getBalance()); // 1500
System.out.println(b.getBalance()); // 700 (서로 상태를 공유하지 않음)
}
}
// 배열로 여러 객체를 관리할 수도 있다.
// 배열은 해당 객체의 참조값을 담는다.
BankAccount[] accounts = new BankAccount[3];
accounts[0] = new BankAccount("Kim", 0);
accounts[1] = new BankAccount("Lee", 100);
accounts[2] = new BankAccount("Park", 200);
1.2 인스턴스화와 메모리 사용 (힙, 메서드 영역, 콜 스택)

- 클래스가 아직 로드되지 않았다면 로딩/연결/초기화(정적 초기화)
- 힙에 메모리 할당(필드가 기본값으로 0/false/null)
- 명시적 필드 초기화 → 생성자 호출
- 참조(레퍼런스)가 스택의 지역변수에 저장
- 힙(Heap):
new 키워드로 생성한 객체들이 올라가는 공간. GC가 관리.