Java의 정적 변수와 비정적 변수
발행: (2026년 1월 14일 오전 12:45 GMT+9)
2 min read
원문: Dev.to
Source: Dev.to
비정적(인스턴스) 변수
Java에서 비정적 변수는 static 키워드를 사용하지 않고 클래스 내부에 선언하지만 메서드 안에는 선언하지 않습니다. 클래스의 각 객체는 해당 변수의 별도 복사본을 갖게 됩니다.
핵심 포인트
- 객체가 생성될 때 생성됨
- 각 객체마다 다른 값을 가짐
- 힙 메모리에 저장됨
- 객체 참조를 통해 접근함
예시
class Student {
int marks;
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.marks = 80;
s2.marks = 90;
System.out.println(s1.marks); // 80
System.out.println(s2.marks); // 90
}
}
여기서 marks는 비정적 변수이므로 각 Student 객체가 자신의 값을 가집니다.
정적 변수
정적 변수는 개별 객체가 아니라 클래스 자체에 속합니다.
핵심 포인트
- 클래스가 로드될 때 한 번 생성됨
- 모든 객체가 공유함
- 메서드 영역에 저장됨
- 클래스 이름을 사용하여 접근하는 것이 권장됨
예시
public class Employee {
String name;
int salary;
static String company_name = "TCS";
public static void main(String[] args) {
Employee mukesh = new Employee();
mukesh.name = "Mukesh kumar";
mukesh.salary = 10000;
Employee hari = new Employee();
hari.name = "Hari krishnan";
hari.salary = 20000;
}
}