1. 객체지향(OOP) 기본 개념

1.1 객체, 클래스, 인스턴스

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 인스턴스화와 메모리 사용 (힙, 메서드 영역, 콜 스택)

image.png

  1. 클래스가 아직 로드되지 않았다면 로딩/연결/초기화(정적 초기화)
  2. 힙에 메모리 할당(필드가 기본값으로 0/false/null)
  3. 명시적 필드 초기화 → 생성자 호출
  4. 참조(레퍼런스)가 스택의 지역변수에 저장