Java에서 Static이란 키워드는 메모리에 한번 할당되어 프로그램이 종료될 때 해제되는 것을 의미한다.
Employee
public class Employee {
public static int serialNum = 1000; // 초기 생성번호
private int employeeId; // 사원ID
private String employeeName;// 사원 이름
private String department; // 부서
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
EmployeeTest
public class EmployeeTest { public static void main(String[] args) { Employee employeeLee = new Employee(); employeeLee.setEmployeeName("이순신"); System.out.println(employeeLee.serialNum); Employee employeeKim = new Employee(); employeeKim.setEmployeeName("김유신"); employeeKim.serialNum++; System.out.println(employeeLee.serialNum); System.out.println(employeeKim.serialNum); } }
1000
1001
1001
public class Employee {
private static int serialNum = 1000;
private int employeeId;
private String employeName;
private String department;
public Employee() {
serialNum++; // 사원번호(serialNum)가 증가한다.
employeeId = serialNum; // 증가한 사원번로를 따로 저장하여준다.
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeName() {
return employeName;
}
public void setEmployeName(String employeName) {
this.employeName = employeName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
}
EmployeeTest
public class EmployeeTest { public static void main(String[] args) { Employee employeeLee = new Employee(); employeeLee.setEmployeName("이순신"); Employee employeeKim = new Employee(); employeeKim.setEmployeName("김유신"); // employeeKim.serialNum++; System.out.println(employeeLee.getEmployeName() +"님의 사번은" + employeeLee.getEmployeeId()); // 1001 System.out.println(employeeKim.getEmployeName() +"님의 사번은" + employeeKim.getEmployeeId()); // 1002 } }
이순신님의 사번은1001
김유신님의 사번은1002