static 변수는 프로그래밍에서 중요한 개념 중 하나. 클래스 변수라고도 불리며 클래스의 모든 인스턴스가 공유하는 변수, 즉 객체가 동일한 static변수의 값을 공유함 객체를 생성하기 전에도 먼저 사용할 수 있다.
static 코드 -NumberPrinter
package com.tenco_static;
public class NumberPrinter {
//static 변수는 모든 인스턴스가 공유하는 변수를 만들 때 사용할 수 있다
//static 심지어 객체를 생성하기 전에도 먼저 사용할 수 있다 (클래스 변수라고도 불림)
private int id; // 기기의 고유 식별자
static int waitNumber; // 대기번호
public NumberPrinter(int id) {
this.id = id;
this.waitNumber = 1;
}
//번호표를 출력
public void printWaitNumber() {
System.out.println(id + " 기기의 대기 순번은 : " + waitNumber); //번호표 출력
waitNumber++;
}
}
-NumberPrinterMainTest
package com.tenco_static;
public class NumberPrinterMainTest {
public static void main(String[] args) {
//static --> 메모리 영역(Method area, static, classArea)
// static 변수에 특징은 모든 객체가 공유하는 변수가 된다.
// 객체를 생성하지 않아도 클래스 이름으로 접근할 수 있다.
// NumberPrinter numberPrinter1 = new NumberPrinter(1);
// NumberPrinter numberPrinter2 = new NumberPrinter(2);
// numberPrinter1.printWaitNumber();
// numberPrinter2.printWaitNumber();
//static 변수는 클래스 변수라고도 불림
int number = NumberPrinter.waitNumber + 10;
System.out.println("number : " + number);
}
}
-Employee
package com.tenco_static;
public class Employee {
//static 변수 : 클래스 차원에서 관리하며 모든 객체가 공유할 수 있다
//프로그램 시작 시 Method Area(static)에 생성됨
public static int seriaNumber = 100;
private String name; //사원이름
private int employeeId; //사원고유번호
public Employee(String name) {
this.name = name;
//새로운 사원이 들어올 때 마다 공용 번호를 하나 올리고 내 사원번호에 저장
this.employeeId = seriaNumber;
seriaNumber++;
}
public void showInfo() {
System.out.println("사원이름 " + name);
System.out.println("사원 번호 " + employeeId);
System.out.println("공용 번호 즉 다음 사원 예정 번호 " + seriaNumber);
}
}
-EmployeeMainTest
package com.tenco_static;
public class EmployeeMainTest {
public static void main(String[] args) {
//static변수는 인스턴스 생성 전에도 클래스 이름으로 접근 가능
System.out.println("시작 시리얼 번호 : " + Employee.seriaNumber);
Employee emp1 = new Employee("홍길동");
emp1.showInfo();
Employee emp2 = new Employee("이순신");
emp2.showInfo();
Employee emp3 = new Employee("강감찬");
emp3.showInfo();
//생성자 3번 호출
// emp1.showInfo(); //출력
// emp2.showInfo();
// emp3.showInfo();
}
}