2012년 12월 29일 토요일

[Ch08Ex04] Static Method

클래스 명으로 Static 메소드 호출하기.

Static Method never use "THIS" reference nor "Instance variable".
This는 객체를 생성하게되면, 메소드에서 객체마가 그 객체가할당된 힙영역의 주소를 관리함.
메소드 내부에서 어떤 객체에 대해서 호출 되었는지 구분하려고 , 자바컴파일러에 의해서 제공된다는 구분하는 역할로 this라는 레퍼런스 변수를 사용한다.
인스턴스 메소드가 어떤 객체에 의해서 호출되었는지를 구분하기 위해서 "THIS"가 메소드 내부에서 사용된다. 반명 Static 메소드는 객체에 종속적이지 않고 클래스 단위로 접근하는 메소드이므로 this가 사용 될 수 없다.


Result

   total : 0
   total : 10
   total : 20


Sample code 

File name :Ch08Ex04.java

public class Ch08Ex04 {

public static void main(String[] args) {
Account.showTotal();

Account acc01=new Account(10);
Account.showTotal();

Account acc02 = new Account(10);
Account.showTotal();


}

}





File name : Account.java


class Account {

int count;
static int total;
// Cannot make a static reference to the non-static field Account.total
// if missing "static"
// or 전체가 10으로 나옴.

Account(int amount){
count +=amount;
total +=amount;
}

static void showTotal(){
System.out.println("   total : "+total);
}

}


Applied Code 

Result of Applied code :

    total : 0
    total : 10
    total : 20

Code : 

File name :Ch08Ex04.java


public class Ch08Ex04 {

public static void main(String[] args) {
System.out.println("    total : " +Account.total);
Account acc01=new Account(10);
System.out.println("    total : " +acc01.total);
Account acc02= new Account(10);
System.out.println("    total : " +acc02.total);

}

}

File name : Account.java

class Account {

int count;
static int total;
// Cannot make a static reference to the non-static field Account.total
// if missing "static"
// or 전체가 10으로 나옴.
Account(int amount){
count +=amount;
total +=amount;
}




Reference book : 이클립스로 배우는 Java 6 Programming/ 임종권, 전병찬/ 가메출판사

댓글 없음:

댓글 쓰기