
자바의 static과 this는 초반에 헷갈리기 쉬운데, 아주 쉽게 핵심을 잡고 파일을 분리한 실습 예제로 바로 이해할 수 있게 정리해드리겠습니다. 단계별 설명 후, 각각 클래스 파일로 분리한 코드와 예상 출력, 중요한 포인트를 함께 드립니다.
핵심 요약(한눈에)
- static: 클래스 레벨 멤버. 객체(인스턴스)마다 따로 있지 않고 클래스 하나에만 존재합니다. 모든 인스턴스가 공유합니다.
- this: 현재 객체(인스턴스)를 가리키는 참조. 보통 생성자나 메서드에서 필드와 매개변수 이름이 같을 때 구분하거나, 현재 객체를 반환할 때 사용합니다.
예제 1 — static의 동작 (파일 분리)
목적: 여러 인스턴스가 같은 값을 '공유'하는 것을 보여줌.
파일: Counter.java
java
public class Counter {
// static 변수: 클래스 당 하나만 존재
public static int totalCount = 0;
// 인스턴스 메서드: 각 객체에서 호출 가능
public void increment() {
totalCount++; // 모든 객체가 공유하는 변수
}
}
파일: MainStaticExample.java
java
public class MainStaticExample {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter();
a.increment();
System.out.println("a.increment 후 totalCount = " + Counter.totalCount);
b.increment();
System.out.println("b.increment 후 totalCount = " + Counter.totalCount);
// 클래스명.static변수로 접근하는 것이 권장되는 사용법
Counter.totalCount = 100;
System.out.println("직접 설정 후 totalCount = " + Counter.totalCount);
}
}
예상 출력:
- a.increment 후 totalCount = 1
- b.increment 후 totalCount = 2
- 직접 설정 후 totalCount = 100
설명 포인트:
- a와 b는 서로 다른 객체지만 totalCount는 같은 값(클래스에 하나)이라 서로 누적됩니다.
- static 변수는 클래스명.변수명 으로 접근하는 것이 명확합니다.
예제 2 — this의 사용 (파일 분리)
목적: 필드와 매개변수 이름 충돌 해결, 현재 객체 참조, 메서드 체이닝 예시
파일: Person.java
java
public class Person {
private String name;
private int age;
// 생성자: 매개변수 이름과 필드 이름이 같을 때 this로 구분
public Person(String name, int age) {
this.name = name; // this.name은 필드, name은 매개변수
this.age = age;
}
// 메서드 체이닝을 위해 this 반환
public Person setName(String name) {
this.name = name;
return this;
}
public Person setAge(int age) {
this.age = age;
return this;
}
public void printInfo() {
System.out.println("이름: " + this.name + ", 나이: " + this.age);
}
}
파일: MainThisExample.java
java
public class MainThisExample {
public static void main(String[] args) {
// 생성자에서 this 사용 예
Person p = new Person("철수", 10);
p.printInfo();
// 메서드 체이닝 (setName, setAge가 this 반환)
p.setName("영희").setAge(11);
p.printInfo();
}
}
예상 출력:
- 이름: 철수, 나이: 10
- 이름: 영희, 나이: 11
설명 포인트:
- 생성자에서 this.name = name; 처럼 쓰면 필드(객체의 속성)와 매개변수를 명확히 구분합니다.
- this를 반환하면 메서드 체이닝(한 줄로 여러 설정)을 할 수 있습니다.
예제 3 — static과 this를 함께 보여주는 예 (파일 분리)
목적: static(클래스 공유)과 this(현재 객체)를 동시에 이해
파일: Student.java
java
public class Student {
private String name;
private int id; // 학생 고유 번호(인스턴스 필드)
// static 변수: 학생 전체 수를 카운트
public static int studentCount = 0;
public Student(String name, int id) {
this.name = name;
this.id = id;
Student.studentCount++; // 새 학생이 만들어질 때 전체 수 증가
}
public void show() {
System.out.println("학생: " + this.name + " (ID: " + this.id + ")");
System.out.println("전체 학생 수(공유): " + Student.studentCount);
}
}
파일: MainStudentExample.java
java
public class MainStudentExample {
public static void main(String[] args) {
Student s1 = new Student("민수", 1);
s1.show();
Student s2 = new Student("지우", 2);
s2.show();
// studentCount는 클래스 레벨이므로 클래스명으로 접근 가능
System.out.println("최종 전체 학생 수: " + Student.studentCount);
}
}
예상 출력(요약):
- 학생: 민수 (ID: 1) 전체 학생 수(공유): 1
- 학생: 지우 (ID: 2) 전체 학생 수(공유): 2
- 최종 전체 학생 수: 2
설명 포인트:
- 각 Student 객체는 자신의 name과 id를 갖고(this 사용).
- studentCount는 모든 Student가 공유하는 값(static).
자주 하는 실수와 팁
- static 변수로 인스턴스별 데이터를 저장하려 하지 마세요. (예: 각 객체의 이름을 static으로 만들면 덮어쓰기 발생)
- static 메서드(static 함수) 안에서는 this를 사용할 수 없습니다. static은 클래스 레벨이므로 '현재 객체' 개념이 없기 때문입니다.
- 생성자나 인스턴스 메서드에서 필드와 매개변수 이름이 같을 때는 this를 항상 사용해 구분하세요.
- static은 프로그램 시작 시점에 메모리 영역에 올라가고(클래스 로드 시), 인스턴스 필드는 객체가 생성될 때마다 새로 생깁니다.
'Java_language' 카테고리의 다른 글
| 클래스 변수 vs 인스턴스 (0) | 2025.12.01 |
|---|---|
| 캡슐화 (private) (0) | 2025.12.01 |
| 자바 접근제어자(Access Modifier) (0) | 2025.12.01 |
| BankAccount 클래스 (0) | 2025.11.27 |
| 클래스를 활용한 학생 정보 출력 프로그램 (0) | 2025.11.26 |