μΈμ€ν΄μ€ & static
μΈμ€ν΄μ€(Instance)λ?
ν΄λμ€λ₯Ό κΈ°λ°μΌλ‘ μμ±λ κ°μ²΄λ₯Ό μΈμ€ν΄μ€(Instance)λΌκ³ ν©λλ€.
κ°μ²΄λ ν΄λμ€μ μ€μ²΄νλ ννλ‘, λ©λͺ¨λ¦¬μ ν λΉλμ΄ μ€μ λ‘ μ¬μ©ν μ μλ μνκ° λ©λλ€.
// Person ν΄λμ€
class Person {
String name;
int age;
void introduce() {
System.out.println("μλ
νμΈμ, μ λ " + name + "μ΄κ³ , " + age + "μ΄μ
λλ€.");
}
}
// λ©μΈ λ©μλμμ μΈμ€ν΄μ€ μμ±
public class Main {
public static void main(String[] args) {
// person1μ Person ν΄λμ€μ μΈμ€ν΄μ€
Person person1 = new Person();
person1.name = "νκΈΈλ";
person1.age = 25;
person1.introduce();
// person2λ Person ν΄λμ€μ μΈμ€ν΄μ€
Person person2 = new Person();
person2.name = "κΉμ² μ";
person2.age = 30;
person2.introduce();
}
}
Java
볡μ¬
staticμ΄λ?
staticμ 'κ³ μ λ'μ΄λΌλ μλ―Έλ‘, μλ°μμλ ν΄λμ€μ κ³ μ λ λ©€λ²λ₯Ό μ μΈν λ μ¬μ©ν©λλ€.
static λ³μ (ν΄λμ€ λ³μ)
static λ³μλ λͺ¨λ μΈμ€ν΄μ€κ° 곡μ νλ λ³μμ
λλ€. μΈμ€ν΄μ€ λ³μμ λ¬λ¦¬ ν΄λμ€κ° λ©λͺ¨λ¦¬μ λ‘λλ λ ν λ²λ§ μμ±λμ΄ λͺ¨λ μΈμ€ν΄μ€μμ κ°μ κ°μ μ°Έμ‘°ν©λλ€.
class Counter {
// μΈμ€ν΄μ€ λ³μ
int instanceCount = 0;
// ν΄λμ€ λ³μ (static λ³μ)
static int staticCount = 0;
public Counter() {
instanceCount++; // κ° μΈμ€ν΄μ€λ§λ€ μ¦κ°
staticCount++; // λͺ¨λ μΈμ€ν΄μ€κ° 곡μ νμ¬ μ¦κ°
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
System.out.println("c1 μΈμ€ν΄μ€ μΉ΄μ΄νΈ: " + c1.instanceCount); // 1
System.out.println("c1 static μΉ΄μ΄νΈ: " + Counter.staticCount); // 1
Counter c2 = new Counter();
System.out.println("c2 μΈμ€ν΄μ€ μΉ΄μ΄νΈ: " + c2.instanceCount); // 1
System.out.println("c2 static μΉ΄μ΄νΈ: " + Counter.staticCount); // 2
// 첫 λ²μ§Έ μΈμ€ν΄μ€μ static λ³μλ λ³κ²½λ¨
System.out.println("c1 static μΉ΄μ΄νΈ: " + c1.staticCount); // 2
}
}
Java
볡μ¬
static λ©μλ (ν΄λμ€ λ©μλ)
static λ©μλλ μΈμ€ν΄μ€ μμ± μμ΄ ν΄λμ€ μ΄λ¦μΌλ‘ μ§μ νΈμΆν μ μλ λ©μλμ
λλ€.
class MathUtils {
// static λ©μλ
static int add(int a, int b) {
return a + b;
}
// μΈμ€ν΄μ€ λ©μλ
int multiply(int a, int b) {
return a * b;
}
}
public class Main {
public static void main(String[] args) {
// static λ©μλλ μΈμ€ν΄μ€ μμ± μμ΄ νΈμΆ κ°λ₯
int sum = MathUtils.add(5, 3);
System.out.println("ν©κ³: " + sum); // 8
// μΈμ€ν΄μ€ λ©μλλ μΈμ€ν΄μ€ μμ± ν νΈμΆ κ°λ₯
MathUtils utils = new MathUtils();
int product = utils.multiply(5, 3);
System.out.println("κ³±: " + product); // 15
}
}
Java
볡μ¬
μΈμ€ν΄μ€μ staticμ μ£Όμ μ°¨μ΄μ
κ΅¬λΆ | μΈμ€ν΄μ€ λ©€λ² | static λ©€λ² |
μμ± μμ | κ°μ²΄ μμ± μ | ν΄λμ€ λ‘λ© μ |
λ©λͺ¨λ¦¬ ν λΉ | ν μμ | λ©μλ μμ(μ μ μμ) |
μ¬μ© λ°©λ² | κ°μ²΄ μμ± ν μ°Έμ‘°λ³μλ‘ μ κ·Ό | ν΄λμ€ μ΄λ¦μΌλ‘ μ§μ μ κ·Ό |
μλͺ
μ£ΌκΈ° | κ°μ²΄κ° μλ©Έλλ©΄ ν¨κ» μλ©Έ | νλ‘κ·Έλ¨μ΄ μ’
λ£λ λκΉμ§ μ μ§ |
곡μ μ¬λΆ | κ° μΈμ€ν΄μ€λ§λ€ λ³λ μμ± | λͺ¨λ μΈμ€ν΄μ€κ° 곡μ |
static μ¬μ© μ μ£Όμμ¬ν
β’
static λ©μλλ μΈμ€ν΄μ€ λ³μλ₯Ό μ§μ μ¬μ©ν μ μμ΅λλ€.
β’
static λ©μλλ this ν€μλλ₯Ό μ¬μ©ν μ μμ΅λλ€.
β’
λ©λͺ¨λ¦¬ λμ μνμ΄ μμΌλ―λ‘ κΌ νμν κ²½μ°μλ§ μ¬μ©ν΄μΌ ν©λλ€.
β’
μμ(final static)λ‘ μ£Όλ‘ μ¬μ©λ©λλ€.
β’
μ νΈλ¦¬ν° λ©μλλ 곡ν΅μΌλ‘ μ¬μ©λλ κΈ°λ₯μ ꡬνν λ μ μ©ν©λλ€.