public class Counter {
static int count = 0; // 클래스 변수
public Counter() {
count++;
}
public void printCount() {
System.out.println("현재 객체 수: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
c1.printCount(); // 3
c2.printCount(); // 3
c3.printCount(); // 3
}
}
7. static 메서드 예시
public class MathUtils {
public 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
}
}
[ 실습 ]
✅ 실습 1: User 클래스 만들기
public class User {
private String name;
static int userCount = 0;
public User(String name) {
this.name = name;
userCount++; // 인스턴스 만들 때마다 userCount++ 됨
}
public String getName() {
return name;
}
public static void printUserCount() {
System.out.println("총 사용자 수: " + userCount);
}
}
✅ 실습 2: Main에서 사용
public class Main {
public static void main(String[] args) {
User u1 = new User("홍길동");
User.printUserCount(); // static 메서드 호출
User u2 = new User("김철수");
System.out.println("사용자 1: " + u1.getName());
System.out.println("사용자 2: " + u2.getName());
User.printUserCount(); // static 메서드 호출
}
}
[ 메모 ]
싱글톤 패턴: 프로그램 전체에서 오직 하나의 인스턴스만 존재하게 하는 디자인 패턴
필요 이유: 객체가 하나만 필요하고, 모든 곳에서 그 하나를 써야 할 때
장점: 중복 생성 방지, 일관성 유지, 자원 절약, 어디서든 쉽게 접근 가능 (클래스명.getInstance() )