Static이라고 선언한 total은 클래스 단위당 한개만 생성되어 여러개의 객체가 해당 멤버를 공유하므로 이전 값에 새로운 값이 누적되나, 인스턴스 필드인 count는 개별적으로 따로 메모리 할당을 하기 때문에 개별적으로 10을 갖고 있다.
Acount.total : " +Account.total 은 가능하나
Acount.total : " +Account.count 는 불가능하다.
Static 변수가 아닌 인스턴스 변수는 클래스 명으로 접근 할 수 없다.
(Error : Cannot make a static reference to the non-static field Account.total)
Result :
Acount.total : 0
acc01.total : 10
acc01.count : 10
acc02.total : 20
acc02.count : 10
acc03.total : 30
acc03.count : 10
Sample Code
File name : Account.java
class Account {
int count;
static int total;
Account(int amount){
count +=amount;
total +=amount;
}
}
File name : Ch08Ex03.java
public class Ch08Ex03 {
public static void main(String[] args) {
System.out.println("Acount.total : " +Account.total);
Account acc01=new Account(10);
System.out.println("acc01.total : " +acc01.total);
System.out.println("acc01.count : " +acc01.count);
Account acc02=new Account(10);
System.out.println("acc02.total : " +acc02.total);
System.out.println("acc02.count : " +acc02.count);
Account acc03=new Account(10);
System.out.println("acc03.total : " +acc03.total);
System.out.println("acc03.count : " +acc03.count);
}
}
Reference book : 이클립스로 배우는 Java 6 Programming/ 임종권, 전병찬/ 가메출판사
댓글 없음:
댓글 쓰기