JAVA/언어입문
자바(JAVA) - static 변수 / static 메서드
Sunyoung95
2022. 3. 25. 19:12
static
- static 변수 = 클래스 변수
- statc 메서드 = 클래스 메서드
static 변수
- 역할
- 프로그램에서 단 하나만 존재하는 변수를 설정 (여러개 존재하면 X)
- 여러개의 인스턴스가 같은 메모리의 값을 공유하기 위해 사용
- 인스턴스가 공유하는 변수
- 예시
- Student 클래스 생성
-
위와 같이 class를 만들었을 경우 실행단에서 2개의 인스턴스를 생성한다 했을 때public class Student { int studentID; Stirng studentName; static String position = "student"; }
-
- Student 인스턴스 생성
-
public class StudentTest { public static void main(String[] args) { Student studentLee = new Student(); Student studentKim = new Student(); System.out.println(studentLee.position);// student studentLee.position = "teacher" System.out.println(studentLee.position);// teacher System.out.println(studentLee.position);// teacher // 위처럼 객체로 참조하기보다는 클래스 자체에서 참조하는게 더 좋은 방법! System.out.println(Student.position);// teacher } }
-
- 각 인스턴스를 생성했을 때 메모리 구조는 아래와 같다.
- 데이터영역 : static, 리터럴 등이 생성되는 영역
- 스택메모리 : 지역변수(메서드 안의 변수들 = local variable)가 쓰는 메모리
- 힙메모리 : 인스턴스가 생성될 때마다 사용하는 동적 메모리
- 각 변수들의 생성 시기
- Student 클래스 생성
변수유형 | 선언 위치 | 생성시기 | 소멸시기 | 메모리 |
static 변수 (클래스변수) |
static 예약어를 사용하여 클래스 내부에 선언 | 클래스가 메모리에 올라갈때 프로그램이 처음 시작할 때 |
프로그램이 종료될 때 | 데이터 영역 |
멤버변수 (인스턴스 변수) |
클래스 멤버 변수로 선언 | 인스턴스가 생성될 때 | 인스턴스가 소멸할때 가비지 컬렉터가 메모리를 수거할 때 |
힙 영역 |
지역 변수 (로컬 변수) |
함수 내부에 선언 | 함수가 호출 될 때 | 함수가 종료될 때 | 스택 영역 |
→ 따라서 static 변수는 인스턴스의 생성여부와 상관없이 클래스 이름으로 직접 참조가 가능하다!
static 메서드
- 주로 static 변수를 위한 기능을 제공
public class Student {
int studentID;
String studentName;
// private 이므로 외부에서 직접사용 불가
private static int serialNum = 1000;
public static int getSerialNum() {
// 메소드 안이므로 지역변수선언 가능
int i;
i++;
// 인스턴스의 생성여부가 불확실한 상태에서 멤버변수를 사용하려하면 에러남
studentName="Kim"; // error
serialNum++; //호출할 때마다 1씩 증가된 값이 저장됨
return serialNum;
}
}