Java

자바 프로그래밍 (Java) - 17 : 객체와 클래스 (명시적 생성자 호출 : this, this with constructor)

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

- 명시적 생성자 호출 (this와 생성자(Constructor))

 

한 생성자 안에서, this 키워드를 사용하여 같은 클래스의 다른 생성자를 호출할 수 있다.

 

이것을 명시적 생성자 호출이라고 부른다. 명시적 생성자 호출은 그 생성자 안에서 첫 번째 라인에 위치해야 한다.

 

이는 코드 중복을 해결하기 위해서 사용된다.

 

 

public class Rectangle {

    private int x, y;

    private int width, height;

    public Rectangle(int width, int height) {

        this.x = 0;

        this.y = 0;

        this.width = width;

        this.height = height;

    }

    public Rectangle(int x, int y, int width, int height) {

        this.x = x;

        this.y = y;

        this.width = width;

        this.height = height;

    }

}

 

public class Rectangle {

    private int x, y;

    private int width, height;

    public Rectangle(int width, int height) {

        this(0, 0, width, height);

    }

    public Rectangle(int x, int y, int width, int height) {

        this.x = x;

        this.y = y;

        this.width = width;

        this.height = height;

    }

}