카테고리 없음
7. Java Static 전역(전체영역)변수 사용하기
oioioa
2024. 12. 13. 12:13
클래스의 멤버 변수를 만들때 앞에 static를 입력해주면 해당 변수는 전역변수가 된다
전역변수(Static)는 Heap영역이 아닌 data 영역이라는 메모리에 생긴다.
ex)
package entity;
public class Student {
public String name;
public int id;
public static int serialNumber;
public void print(){
System.out.println("이름 : "+ name +", 아이디 : "+ id);
System.out.println("스태틱 변수의 값 : " + serialNumber);
}
}
import entity.Student;
public class StaticTast {
public static void main(String[] args) {
// 학생 데이터를 저장하려 합니다.
// 홍길동 학생 데이터 생성
Student s1 = new Student();
s1.name = "홍길동";
s1.print();
// static 키워드가 붙어있는 변수는, 메모리 영역이 Data 영역에 생긴다.
// 이것은 무슨 뜻이냐면, 객체 생성 안해도, 이 변수를
// 마음대로 사용할 수 있다는 뜻
Student.serialNumber = Student.serialNumber + 1;
// 김나나 학생 데이터 생성
Student s2 = new Student();
s2.name = "김나나";
s2.print();
// 최철수 학생 데이터 생성
// 김영자 학생 데이터 생성
}
}