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 λ©€λ²μ μ μ½ μ‘°κ±΄
- 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 λ©μλ νΈμΆ κ°λ₯
}
- 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 μ¬μ© λΆκ°
}