- 명시적 생성자 호출 (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; } } |
'Java' 카테고리의 다른 글
자바 프로그래밍 (Java) - 19 : 예외 처리 (try - catch) (0) | 2016.07.13 |
---|---|
자바 프로그래밍 (Java) - 18 : 객체와 클래스 (필드 초기화 및 이름 명명 규칙) (0) | 2016.07.12 |
자바 프로그래밍 (Java) - 16 : 객체와 클래스 (static method, this) (0) | 2016.07.12 |
자바 프로그래밍 (Java) - 15 : 객체와 클래스 (new 연산자, 기본 생성자(Default Constructor), 필드의 기본 값) (0) | 2016.07.12 |
자바 프로그래밍 (Java) - 14 : 객체와 클래스 (생성자, 생성자 오버로딩) (0) | 2016.07.12 |