πŸ“– ν•™μŠ΅ λͺ©ν‘œ

staticκ³Ό final λ³€μˆ˜

static

static λ³€μˆ˜λŠ” ν΄λž˜μŠ€μ— μ†ν•˜λŠ” λ³€μˆ˜λ‘œ, λͺ¨λ“  객체가 κ³΅μœ ν•˜λŠ” λ³€μˆ˜λ₯Ό μ˜λ―Έν•œλ‹€. non-static λ©€λ²„λŠ” 객체가 생성될 λ•Œ, κ°μ²΄λ§ˆλ‹€ non-static 멀버듀이 μƒκΈ°λŠ” 반면, static λ³€μˆ˜λŠ” ν΄λž˜μŠ€λ‹Ή ν•˜λ‚˜λ§Œ μƒμ„±λ˜λ©°, 객체듀에 μ˜ν•΄ κ³΅μœ λœλ‹€λŠ” νŠΉμ§•μ΄ 있으며, μΈμŠ€ν„΄μŠ€λ₯Ό μƒμ„±ν•˜μ§€ μ•Šμ•„λ„ 클래슀 μ΄λ¦„μœΌλ‘œ μ ‘κ·Ό κ°€λŠ₯ν•˜λ‹€.

static λ³€μˆ˜λŠ” μƒμ„±λœ λͺ¨λ“  객체듀에 μ˜ν•΄ λ³€μˆ˜κ°€ κ³΅μœ λ˜λ―€λ‘œ β€œstatic λ©€λ²„μ˜ μ†Œμœ κΆŒμ€ ν΄λž˜μŠ€μ— μžˆλ‹€.”고 μ΄μ•ΌκΈ°ν•˜κΈ°λ„ ν•œλ‹€.

static λ³€μˆ˜λŠ” 두 κ°€μ§€ μ œμ•½ 쑰건을 κ°€μ§€κ³  μžˆλ‹€.

  1. static λ©”μ†Œλ“œλŠ” 였직 static λ©€λ²„λ§Œ μ ‘κ·Ό κ°€λŠ₯ν•˜λ‹€.
    1. μ΄λŠ” 객체가 μƒμ„±λ˜μ§€ μ•Šμ€ μƒν™©μ—μ„œλ„ static λ©”μ†Œλ“œκ°€ 싀행될 수 있기 λ•Œλ¬Έμ— λ°œμƒν•˜λŠ” ν˜„μƒμ΄λ‹€. non-static λ©€λ²„λŠ” 객체 생성 μ‹œμ— 멀버가 μƒμ„±λ˜λŠ” 반면, static λ©”μ†Œλ“œλŠ” ν΄λž˜μŠ€κ°€ JVM에 μ˜ν•΄ λ§Œλ“€μ–΄μ§ˆ λ•Œ, 즉 객체가 생기기 이전에 μƒμ„±λ˜κΈ° λ•Œλ¬Έμ— μ΄λŸ¬ν•œ ν˜„μƒμ΄ λ°œμƒν•œλ‹€.
    2. non-static λ©”μ†Œλ“œλŠ” static 멀버λ₯Ό μ‚¬μš©ν•  수 μžˆλ‹€.
  2. static λ©”μ†Œλ“œλŠ” 객체 없이도 μ‚¬μš© κ°€λŠ₯ν•˜λ―€λ‘œ this 레퍼런슀λ₯Ό μ‚¬μš©ν•  수 μ—†λ‹€.

μ΄λŸ¬ν•œ static λ³€μˆ˜λŠ” λͺ¨λ“  객체듀에 μ˜ν•΄ κ³΅μœ λ˜λŠ” νŠΉμ„±μ΄ μžˆκΈ°μ— μ „μ—­ λ³€μˆ˜μ™€ μ „μ—­ ν•¨μˆ˜λ₯Ό λ§Œλ“€κ±°λ‚˜, 곡유 멀버λ₯Ό λ§Œλ“€κ³ μž ν•  λ•Œ μ‚¬μš©λœλ‹€.

image.png

class Counter {
    static int count = 0; // static λ³€μˆ˜

    Counter() {
        count++; // λͺ¨λ“  객체가 λ™μΌν•œ count 값을 곡유
    }

    void showCount() {
        System.out.println("Count: " + count);
    }
}

public class Main {
    public static void main(String[] args) {
        Counter c1 = new Counter();
        Counter c2 = new Counter();
        Counter c3 = new Counter();

        c1.showCount(); // Count : 3
        c2.showCount(); // Count : 3
        c3.showCount(); // Count : 3
    }
}
class MathUtil {
    static int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        int sum = MathUtil.add(5, 10); // 클래슀λͺ…μœΌλ‘œ 직접 호좜
        System.out.println("Sum: " + sum); // Sum : 15
    }
}

final

final ν‚€μ›Œλ“œλŠ” 기본적으둜 변경을 κΈˆμ§€ν•˜λŠ” 역할을 ν•˜λ©°, λ³€μˆ˜, λ©”μ„œλ“œ, ν΄λž˜μŠ€μ— μ μš©λ˜μ–΄ 각각 λ‹€λ₯Έ 의미λ₯Ό μ§€λ‹Œλ‹€.

  1. final λ³€μˆ˜ : μƒμˆ˜ μ •μ˜