자바에선 생성자 또한 오버로딩할 수 있다.
class Rectangle{
int x;
int y;
int width;
int height;
Rectangle(){
this(1,2,3,4);
}
Rectangle(int width, int height){
this(3,4,width,height);
}
Rectangle(int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}
public class ConstructorOverloadingPractice {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
Rectangle rectangle2 = new Rectangle(10,20);
Rectangle rectangle3 = new Rectangle(10,20,30,40);
System.out.println(rectangle.x + " " + rectangle.y + " " + rectangle.width + " " + rectangle.height);
System.out.println(rectangle2.x + " " + rectangle2.y);
System.out.println(rectangle3.x + " " + rectangle3.y + " " + rectangle3.width + " " + rectangle3.height);
}
}
다음과 같이 this를 통해 생성자 오버로딩을 할 수 있다. 기본 생성자의 this()를 보면 매개 변수가 네 개이다.
그럼 매개 변수가 네 개인 생성자를 호출하여 사용할 수 있다. 만약 두 개일 경우 두 개인 생성자를 호출한다.
this.x는 rectangle 클래스의 x를 가르키고 =x의 x는 매개변수 x를 가르킨다.
이름이 같아 혼동하지 않기 위해 this키워드를 사용한다.
만약 this 키워드를 사용하기 싫다면 매개변수의 x를 a나 같이 다른 값으로 바꾸고
x = a와 같이 사용해도 되긴한다. 하지만 가독성이 떨어지므로 this를 쓰자.
'자바' 카테고리의 다른 글
| 다양한 방법으로 사칙연산 계산기 만들기 (0) | 2025.02.27 |
|---|---|
| 자바 최신 문법 활용해보기 (스트림, 옵셔널, 스위치 표현식, 레코드, 인스턴스오프) (0) | 2025.02.20 |
| 자바 오버로딩(Overloading) (0) | 2024.05.27 |
| 자바 생성자 (0) | 2024.05.27 |
| 자바 접근 제어자 public protected default private (0) | 2024.05.27 |