static ν€μλλ λͺ¨λ κ°μ²΄κ° ν¨κ» μ¬μ©νλ λ³μλ λ©μλλ₯Ό λ§λ€λ μ¬μ©λλ€.κ°μ²΄(μΈμ€ν΄μ€)λ₯Ό λ§λ€μ§ μμλ ν΄λμ€ μ΄λ¦μ ν΅ν΄ μ¬μ© κ°λ₯staticλ³μμ λ©μλλ ν λ²λ§ μμ±λκ³ Method Areaμ μ μ₯λλ€.staticν€μλλ₯Ό ν΅ν΄ μμ±λλ€.ν΄λμ€λͺ
.λ³μλͺ
, ν΄λμ€λͺ
.λ©μλλͺ
()public class Cat {
static int cat; //ν΄λμ€ λ³μ (λͺ¨λ κ°μ²΄κ° 곡μ )
String name; //μΈμ€ν΄μ€ λ³μ (κ° κ°μ²΄λ§λ€ λ€λ¦)
public Cat(String name) {
this.name = name;
cat++; //ν΄λμ€ λ³μλ κ°μ²΄ μμ΄λ μ κ·Ό κ°λ₯
}
public void showCat(){ //μΈμ€ν΄μ€ λ©μλ
System.out.println("κ³ μμ΄μ μ΄λ¦: " + name);
}
public static void printCat() { //ν΄λμ€ λ©μλ
System.out.println("κ³ μμ΄μ μλ: " + cat);
}
}
public class Main {
public static void main(String[] args) {
Cat.printCat(); //ν΄λμ€ λ©μλ νΈμΆ -> 0
Cat cat1 = new Cat("κΈΈλ₯μ΄1"); //
Cat cat2 = new Cat("κΈΈλ₯μ΄2");
cat1.showCat(); //μΈμ€ν΄μ€ λ©μλ νΈμΆ
cat2.showCat(); //μΈμ€ν΄μ€ λ©μλ νΈμΆ
Cat.printCat(); //ν΄λμ€ λ©μλ νΈμΆ -> 2
}
}
thisλ μλ€.static λ³μμ λ©λͺ¨λ¦¬λ νλ‘κ·Έλ¨μ΄ μ’
λ£λ λκΉμ§ λ©λͺ¨λ¦¬μ μ μ§λλ€.static λ¨μ©μ λ©λͺ¨λ¦¬ λλΉλ‘ μ΄μ΄μ§λ€.static final ν€μλλ₯Ό μ¬μ©ν΄ μ μΈνλ€.static μΌλ‘ μ μΈλ λ³μλ νλ‘κ·Έλ¨ μμμ ν λ²λ§ μ΄κΈ°νλκ³ λͺ¨λ μΈμ€ν΄μ€μμ κ°μ κ°μ 곡μ νλ€.PI(μμ£Όμ¨)public class Circle {
final static double PI = 3.14159; // β
μμ μ μΈ
}System.out.println("μμνμ©: " + Circle.PI);final, private final(κΆμ₯)λ‘ μ μΈνλ€.public final class Person {
private final String name;
private final int age;
// μμ±μ
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// κ²ν° λ©μλ
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
λΆλ³ κ°μ²΄λ λ΄λΆ κ°μ λ°κΏ μ μκΈ° λλ¬Έμ, μμ μ΄ νμν κ²½μ° μμ λ κ°μ κ°μ§ μ κ°μ²΄λ₯Ό λ§λ€μ΄ μ¬μ©ν΄μΌ νλ€.
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter
public String getName() { return name; }
public int getAge() { return age; }
// κ°μ λ°κΎΈλ λμ μλ‘μ΄ κ°μ²΄λ₯Ό λ§λ€μ΄ 리ν΄
public Person withAge(int newAge) {
return new Person(this.name, newAge);
}
}