static ν€μλ
π 1. static ν€μλμ μλ―Έ
staticμ "μ μ μΈ"μ΄λΌλ μλ―Έλ‘, staticμ λΆμ΄λ©΄ κ°μ²΄(instance)μ κ΄κ³μμ΄ ν΄λμ€(class) λ¨μλ‘ κ΄λ¦¬λλ€λ λ»μ΄λ€!
μ¦, ν΄λμ€κ° λ©λͺ¨λ¦¬μ λ‘λλ λ ν λ²λ§ μμ±λλ©°, λͺ¨λ κ°μ²΄κ° 곡μ νλ€.
β 2. static ν€μλμ μ¬μ©
1οΈβ£ static λ³μ (ν΄λμ€ λ³μ)
- λͺ¨λ κ°μ²΄κ° 곡μ νλ λ³μ! (μΈμ€ν΄μ€μ κ΄κ³ μμ)
- ν΄λμ€λͺ .λ³μλͺ μΌλ‘ μ κ·Ό κ°λ₯
- κ°μ²΄λ₯Ό μμ±νμ§ μμλ μ¬μ© κ°λ₯
π μμ
class Counter {
static int count = 0; // λͺ¨λ κ°μ²΄κ° 곡μ νλ λ³μ
Counter() {
count++; // μμ±λ λλ§λ€ count μ¦κ°
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.count); // μΆλ ₯: 2
}
}
β countλ static λ³μμ΄λ―λ‘ λͺ¨λ Counter κ°μ²΄κ° 곡μ
β c1, c2κ° μμ±λ λλ§λ€ count κ°μ΄ μ¦κ°
β Counter.countμ²λΌ ν΄λμ€λͺ μΌλ‘ μ§μ μ κ·Ό κ°λ₯
2οΈβ£ static λ©μλ (ν΄λμ€ λ©μλ)
- κ°μ²΄ μμ΄ νΈμΆ κ°λ₯! (μΈμ€ν΄μ€ λ³μ β)
- ν΄λμ€λͺ .λ©μλλͺ ()μΌλ‘ νΈμΆ κ°λ₯
- μΈμ€ν΄μ€ λ³μ/λ©μλμ μ κ·Ό λΆκ°
- μ£Όλ‘ μ νΈμ± λ©μλ, ν©ν 리 λ©μλμμ μ¬μ©
π μμ
class MathUtils {
static int square(int x) {
return x * x;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtils.square(5);
System.out.println(result); // μΆλ ₯: 25
}
}
β μ£Όμ : static λ©μλ λ΄λΆμμλ μΈμ€ν΄μ€ λ³μ(this.λ³μλͺ )λ₯Ό μ¬μ©ν μ μμ!
β κ°μ²΄(μΈμ€ν΄μ€)κ° μμ±λ λλ§λ€ κ°λ³μ μΌλ‘ μμ±λλ κ².
π μμ
class Example {
int x = 10;
static void printX() {
System.out.println(x); // μ€λ₯! (μΈμ€ν΄μ€ λ³μ μ κ·Ό λΆκ°)
}
}
3οΈβ£ static λΈλ‘ (ν΄λμ€ μ΄κΈ°ν λΈλ‘)
- ν΄λμ€κ° λ‘λλ λ ν λ²λ§ μ€νλ¨!
- μ£Όλ‘ static λ³μ μ΄κΈ°ν μ©λλ‘ μ¬μ©
- main() λ³΄λ€ λ¨Όμ μ€νλ¨
π μμ
class Config {
static String appName;
static { // ν΄λμ€κ° λ‘λλ λ ν λ² μ€νλ¨
appName = "My App";
System.out.println("Config Loaded!");
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Config.appName); // My App
}
}
β static {} λΈλ‘μ ν΄λμ€κ° λ‘λλ λ ν λ² μ€νλ¨
β λ°μ΄ν°λ² μ΄μ€ μ°κ²° μ€μ , μμ μ΄κΈ°ν λ±μ μ¬μ©
4οΈβ£ static λ΄λΆ ν΄λμ€ (μ€μ²© ν΄λμ€)
- λ°κΉ₯ ν΄λμ€μ μΈμ€ν΄μ€ μμ΄ μ¬μ© κ°λ₯!
- static ν΄λμ€λ μΈλΆ ν΄λμ€μ μΈμ€ν΄μ€ λ³μ μ¬μ© λΆκ°
- λ°κΉ₯ν΄λμ€.λ΄λΆν΄λμ€ ννλ‘ μ κ·Ό
π μμ
class Outer {
static class Inner {
void display() {
System.out.println("Hello from static inner class");
}
}
}
public class Main {
public static void main(String[] args) {
Outer.Inner obj = new Outer.Inner(); // κ°μ²΄ μμ± κ°λ₯
obj.display();
}
}
π κ²°λ‘
staticμ μ μ (ν΄λμ€ λ¨μ κ΄λ¦¬)λΌλ 곡ν΅μ μ΄ μμ§λ§, κ°κ° μ μ©λλ λ°©μμ΄ λ€λ¦!
static μμ | μ€λͺ | νΉμ§ |
static λ³μ | λͺ¨λ κ°μ²΄κ° 곡μ νλ λ³μ | ν΄λμ€ λ‘λ μ 1λ²λ§ μμ± |
static λ©μλ | κ°μ²΄ μμ΄ νΈμΆ κ°λ₯ν λ©μλ | μΈμ€ν΄μ€ λ³μ μ¬μ© λΆκ° |
static λΈλ‘ | ν΄λμ€ λ‘λ μ 1λ² μ€νλλ μ΄κΈ°ν λΈλ‘ | main()λ³΄λ€ λ¨Όμ μ€ν |
static λ΄λΆ ν΄λμ€ | λ°κΉ₯ ν΄λμ€μ μΈμ€ν΄μ€ μμ΄ μ¬μ© κ°λ₯ | λ°κΉ₯ ν΄λμ€μ μΈμ€ν΄μ€ λ³μ μ κ·Ό β |
β 곡μ ν΄μΌ νλ λ°μ΄ν°λ static λ³μλ‘!
β κ°μ²΄ μμ΄ νΈμΆν λ©μλλ static λ©μλλ‘!
β ν΄λμ€ λ‘λ© μ μ΄κΈ°νν μμ
μ static λΈλ‘μΌλ‘!