junghyunlyoo staticVsNonstatic - GANGNAM-JAVA/JAVA-STUDY GitHub Wiki

static 멀버 μ„ μ–Έ 방법

class StaticSample {
  int n; // non-static ν•„λ“œ
  void g() {...} // non-static λ©”μ„œλ“œ

  static int m; // static ν•„λ“œ
  static void f() {...} // static λ©”μ„œλ“œ
}

static 멀버 vs non-static 멀버

static 멀버 non-static 멀버
μƒμ„±λ˜λŠ” 곡간 λ©€λ²„λŠ” ν΄λž˜μŠ€λ‹Ή ν•˜λ‚˜κ°€ μƒμ„±λœλ‹€. λ©€λ²„λŠ” κ°μ²΄λ§ˆλ‹€ λ³„λ„λ‘œ μ‘΄μž¬ν•œλ‹€.
μƒμ„±λ˜λŠ” μ‹œκ°„ ν΄λž˜μŠ€κ°€ λ‘œλ”©λ  λ•Œ μƒμ„±λœλ‹€. 객체가 생성될 λ•Œ μƒμ„±λœλ‹€.
객체간 곡유 o x

static 멀버가 μƒμ„±λ˜λŠ” 곡간

java 7κΉŒμ§€λŠ” java heap λ‚΄μ˜ permanent μ˜μ—­μ— μ €μž₯λ˜μ—ˆλ‹€. ν•˜μ§€λ§Œ GC의 λŒ€μƒμ΄ λ˜μ§„ μ•Šμ•˜λ‹€.

ν•˜μ§€λ§Œ java 8λΆ€ν„° heap의 permanentκ°€ metaspace둜 뢄리 λ˜μ—ˆκ³ , permanentμ˜μ—­μ— μ €μž₯λ˜μ—ˆλ˜ static object듀은 κ·ΈλŒ€λ‘œ heap에 λ‚¨κ²Œ λ˜μ—ˆλ‹€.

그리고 GC의 λŒ€μƒμ΄ λ˜λ„λ‘ μˆ˜μ •λ˜μ—ˆλ‹€.

non-static 멀버가 μƒμ„±λ˜λŠ” 곡간

객체가 생성될 λ•Œ, κ·Έ 객체가 μ†Œμœ ν•˜κ³  μžˆλŠ” non-static 멀버도 μƒμ„±λœλ‹€.

그리고 μƒμ„±λœ κ°μ²΄λŠ” runtime data area λ‚΄μ˜ heap에 μ €μž₯λœλ‹€.

static λ©€λ²„μ˜ μ œμ•½ 쑰건

  1. static λ©€λ²„λŠ” 였직 static λ©€λ²„λ§Œ μ ‘κ·Όν•  수 μžˆλ‹€.

static λ©”μ„œλ“œλŠ” 객체가 μƒμ„±λ˜μ§€ μ•Šμ€ μƒν™©μ—μ„œλ„ μ‚¬μš©μ΄ κ°€λŠ₯ν•˜λ―€λ‘œ 객체에 μ†ν•œ μΈμŠ€ν„΄μŠ€ λ©”μ†Œλ“œ, μΈμŠ€ν„΄μŠ€ λ³€μˆ˜ 등을 μ‚¬μš©ν•  수 μ—†λ‹€.

class StaticMethod {
  int n;
  void f1(int x) { n = x; } // 정상
  void f2(int x) { n = x; } // 정상

  static int m;
  static void s1(int x) { n = x; } // 컴파일 였λ₯˜. static λ©”μ„œλ“œλŠ” non-static ν•„λ“œ μ‚¬μš© λΆˆκ°€
  static void s2(int x) { f1(3); } // 컴파일 였λ₯˜. static λ©”μ„œλ“œλŠ” non-static λ©”μ„œλ“œ μ‚¬μš© λΆˆκ°€

  static void s3(int x) { m = x; } // 정상. static λ©”μ„œλ“œλŠ” static ν•„λ“œ μ‚¬μš© κ°€λŠ₯
  static void s4(int x) { s3(3); } // 정상. static λ©”μ„œλ“œλŠ” static λ©”μ„œλ“œ 호좜 κ°€λŠ₯
}
  1. static λ©”μ„œλ“œμ—μ„œλŠ” this ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•  수 μ—†λ‹€.

thisλŠ” 호좜 λ‹Ήμ‹œ μ‹€ν–‰ 쀑인 객체λ₯Ό κ°€λ¦¬ν‚€λŠ” λ ˆνΌλŸ°μŠ€μ΄λ‹€.

class StaticAndThis {
  int n;
  static int m;
  void f1(int x) { this.n = x; } // 정상
  void f2(int x) { this.m = x; } // non-static λ©”μ„œλ“œμ—μ„œλŠ” static 멀버 μ ‘κ·Ό κ°€λŠ₯
  static void s1(int x) { this.n = x; } // 컴파일 였λ₯˜. static λ©”μ„œλ“œλŠ” this μ‚¬μš© λΆˆκ°€
}