Java

자바 프로그래밍 (Java) - 16 : 객체와 클래스 (static method, this)

n.han 2016. 7. 12. 15:14

- static method

 

static method는 특정 인스턴스 보다는 클래스의 모든 인스턴스와 관련 있는 메서드이다.

 

그런 관점에서 static 변수와 유사하다. static method는 소유하는 객체가 없으며, 인스턴스와 함께 사용되지 않는다.

 

또한 클래스가 인스턴스가 만들어지기 전에도 호출될 수 있게 된다.

 

객체의 런타임에 기반한 인스턴스 함수와 다르게 컴파일 타임에 기반한다.

 

static method의 목적은 그 클래스 내부에 있는 static variable를 호출하기 위함에 있다.

 

static method에서 non – static member에 대한 접근을 제한하고 (컴파일 에러가 발생한다.),

 

non – static method에서 static member에 대한 접근은 권장하지 않는다는 것이다.

 

(static member는 인스턴스화와 관계 없이 접근 가능하기 때문에 Warning 정도한다.)

 

public class Hello {

        int score = 0;

        public static void main(String[] args) {

               score = 2;

               // Cannot make a static reference

               // to the non - static field score

        }

}

 

 

- this

 

this는 현재 겍체에 대한 참조(reference)이다.

 

this는 일반적으로 메서드나 생성자 파라미터에 의해 가려진 필드들을 가리키기 위해 사용한다.

 

다음은 this 키워드를 사용하여 멤버 변수에 접근하는 예제이다.

 

public class Point {

    public int x = 0;

    public int y = 0;

       

    //constructor

    public Point(int x, int y) {

        this.x = x;

        this.y = y;

    }

}