class Employee{
private String name;
public Employee(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
public class Lecture{
public static void main(String[] args){
Employee m[] = new Employee[3];
m[0] = new Employee("Mario");
m[1] = new Employee("Luigi");
m[2] = new Employee("Toad");
System.out.println(m[0].getName());
}
}
클래스 변수에 선언과 동시에 초기화 가능
class Employee {
private String name = "Joe";
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
만약 초기화가 아예 진행되지 않았다면? 그러면 클래스 자체적으로 default constructor가 발동하여
number : 0 / boolean : false / object : null
로 값이 초기화 된다.
하지만 local variable은 반드시 생성과 동시에 초기화 해주어야 한다.
class Employee {
private int salary;
public int getSalary() {
return this.salary;
}
}
public class Lecture {
public static void main(String[] args) {
Employee m = new Employee();
System.out.println(m.getSalary());
int local_var;
System.out.println(local_var); // Error: local variable not initialized!
}
}
final 이라는 것은 constructor에서는 초기화 할 수 있지만 다른 메소드에서는 변경할 수 없는 변수를 이야기 한다.
class Employee{
priate final String name;
public Employee(){
this.name = name;
}
public void setName(String name){
//this.name = name //에러난다.
}
}
static variable 은 클래스 자체에 소속되는 거고 객체별로 속해지는 것이 아님. 그렇기에 공유되고 있는 변수라고 생각할 수 있음.
class Employee{
//초기화 방법1
private static int lastId=0; //static variable
//초기화 방법2
static{
lastId = 0;
}
private int id; //instance variable
public Employee() { id = ++lastId; }
public int getId() { return this.id; }
public int getLastId() { return this.lastId; } # 이건 좋은 방법이 아님
}
public class Lecture {
public static void main(String[] args) {
Employee m = new Employee();
Employee n = new Employee();
System.out.println(m.getId());
System.out.println(n.getId());
System.out.println(m.getLastId());
System.out.println(n.getLastId());
}
}
출력결과 : 1 2 2 2
여기에서 주의할 것이 public int getLastId() { return this.lastId; } 이 함수인데, static variable을 method에서 접근하고 있다. 이러면 java 에서는 에러를 띄어준다.
왜냐하면 java의 garbage collector(gc) 때문이다. gc가 해당 인스턴스 메소드가 끝나는 시점에 메모리를 제거한다면 static variable도 메모리상에서 삭제될 수 있기 때문에 이는 매우 위험하다고 볼 수 있다.