정적변수(Static Variable)
- 클래스로부터 생긴 모든 인스턴스(객체)가 공유하는 변수
- 클래스가 로드될 때 초기화되며, 모든 인스턴스가 동일한 값을 공유
static으로 명시된 멤버변수가 있다면 모두 그 값을 공유한다.
다른 한쪽에서 더하거나 빼도 다른 객체에서 똑같이 반영됨
즉 공유되는 변수이다.
public class Person {
// 정적 변수
public static int population = 0;
public Person() {
population++;
}
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
System.out.println("Population: " + Person.population);
}
}static 변수는 클래스명.변수이름 으로 호출 할 수 있음
세번 객체가 태어났기 때문에 3번 ++ 되어 출력값은 Population: 3 이다
정적 메서드(Static Method)
- 클래스 수준에서 호출할 수 있는 메서드
- 객체 인스턴스 없이 호출 가능
- 인스턴스 변수나 인스턴스 메서드를 참조할 수 없음
public class Person {
public static void greet() {
System.out.println("Hello from Person class!");
}
public static void main(String[] args) {
Person.greet();
}
}사용할 때는 클래스명.메서드() 로 쓴다
정적 메서드에서 정적 변수에 접근
public class Person {
public static int population = 0;
public Person() {
population++;
}
//정적메서드는 '정적변수'에만 접근 가능
//즉, static은 static만 접근 가능
public static void printPopulation() {
System.out.println("Current population: " + population);
}
public static void main(String[] args) {
Person p1 = new Person();
Person p1 = new Person();
Person.printPopulation();
}
}출력값:
Curren population: 2
정적메서드는 인스턴스 변수에 접근할 수 없다!
인스턴스 변수 ↔ 정적(static) 변수
인스턴스 변수 : 각 객체가 고유하게 가지고 있는 변수
public class Person {
// 인스턴스 변수
private String name;
public Person(String name) {
this.name = name;
}
// 정적 메서드
public static void printName() {
// : 오류 정적 메서드에서는 인스턴스 변수에 접근할 수 없음
System.out.println("Name: " + name); // 오류 발생
}
public static void main(String[] args) {
Person p1 = new Person("Alice");
Person.printName();
}
}외워야 할 것
- 정적변수(Static Variable)
: 클래스가 로드 될 때 메모리에 할당되며, 모든 인스턴스가 공유함
인스턴스별로 따로 저장되지 않고 클래스 당 하나만 존재함
모든 인스턴스가 같은 정적변수를 참조하므로
한 인스턴스에서 변수 값을 변경하면 다른 인스턴스에서도 변경된 값이 반영됨
- 정적 메서드(Static Method)
: 클래스 이름을 통해 직접 호출 가능. 인스턴스를 생성하지 않고도 사용 가능
예시: Person.printMessage();
정적 메서드는 인스턴스 변수나 인스턴스 메서드에 접근할 수 없음
클래스 변수나 다른 정적 메서드만 호출 가능
예시: public static void displayCount() {
System.out.println(count);
}
Share article