[Java] Static 변수와 Static 메소드
Static 변수
다음과 같은 HouseLee 클래스가 있다고 하자.
class HouseLee {
String lastname = "이";
}
public class Sample {
public static void main(String[] args) {
HouseLee lee1 = new HouseLee();
HouseLee lee2 = new HouseLee();
}
}
HouseLee 클래스를 만들고 객체를 생성하면 객체마다 객체 변수 lastname을 저장하기 위한 메모리가 별도로 할당된다.
하지만 HouseLee 클래스의 lastname이 어떤 객체이든지 동일한 값인 '이'로 항상 값이 변하지 않는다면 static을 이용해 메모리 낭비를 줄일 수 있다.
또한 static을 사용하는 또 다른 이유는 값을 공유할 수 있기 때문이다. static으로 설정하면 이를 사용하는 모든 객체가 같은 메모리 주소만을 바라보며 값을 공유한다.
아래는 객체를 생성할 때마다 숫자를 증가시키는 Counter 클래스 예시이다.
class Counter {
int count = 0;
Counter() {
this.count++;
System.out.println(this.count);
}
}
public class Sample {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
}
}
// 실행 결과
// 1
// 1
객체 c1, c2를 생성할 때 생성자에서 객체 변수 count의 값을 1씩 증가시켜도 c1, c2와 count는 서로 다른 메모리를 가리키고 있기 때문에 원하는 결과가 나오지 않는 것을 알 수 있다. 객체 변수는 항상 독립적인 값을 가지므로 당연한 결과이다.
따라서 count 변수 앞에 static 키워드를 붙이면 count 값이 공유되어 증가한다.
Static 메소드
class Counter {
static int count = 0;
Counter() {
count++;
System.out.println(count);
}
public static int getCount() {
return count;
}
}
public class Sample {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.getCount()); // 스태틱 메서드는 클래스를 이용하여 호출
}
}
// 실행 결과
// 1
// 2
// 2
Counter 클래스에 getCount()라는 스태틱 메소드를 추가했다. 메소드 앞에 static 키워드를 붙이면 Counter.getCount()와 값이 객체 생성 없이도 클래스를 통해 메서드를 직접 호출할 수 있다.
스태틱 메소드 안에서는 객체 변수 접근이 불가능하다. 이 예에서는 count 변수가 static 변수이기 때문에 스태틱 메소드에서 접근 가능하다.
public class Student {
// Static 변수: 모든 객체가 공유
private static int studentCount = 0;
// 인스턴스 변수: 각 객체마다 별도로 관리
private String name;
// 생성자: 객체 생성 시 호출
public Student(String name) {
this.name = name;
studentCount++; // 새로운 객체 생성 시 studentCount 증가
}
// Static 메소드: studentCount에 접근 (클래스 레벨)
public static int getStudentCount() {
return studentCount;
}
// 인스턴스 메소드: 특정 학생의 정보를 출력
public void printStudentInfo() {
System.out.println("Student Name: " + name);
}
public static void main(String[] args) {
// 객체 생성
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
// Static 메소드 호출 (객체 생성 없이 클래스 이름으로 호출 가능)
System.out.println("Total Students: " + Student.getStudentCount());
// 인스턴스 메소드 호출 (각 객체를 통해 호출)
s1.printStudentInfo();
s2.printStudentInfo();
}
}
출력 결과
Total Students: 2
Student Name: Alice
Student Name: Bob
참조
07-03 스태틱
스태틱(static)은 클래스에서 공유되는 변수나 메서드를 정의할 때 사용된다. 이번 절에서는 스태틱에 대해서 자세히 알아보자. [TOC] ## static 변수 다음과 같…
wikidocs.net