생성자 오버로딩
같은 이름의 생성자를 생성자 시그니쳐(갯수, 순서, 타입)만 다르게 정의하여 호출하는 것.
생성자 오버로딩을 활용하여 세 개의 파라미터를 받는 생성자의 첫 부분에 두 개의 파라미터를 받는 생성자를,
두 개의 파라미터를 받는 생성자의 첫 부분에는 한 개의 파라미터를 받는 생성자를 넣어 간결하게 표현할 수 있다.
※ this(type, type...)
같은 클래스에서 정의된 다른 생성자를 호출하는 키워드
- 호출하려는 생성자의 파라미터의 순서에 맞게 호출하면 된다.
- this생성자 호출은 생성자 첫머리에서만 가능하다.
- 딱 한번만 불러올 수 있다.
package jun03;
class Car{
String model;
String color;
String speed;
int id;
static int number = 0;
public Car(String model) {
this.model = model;
}
public Car(String model, String color) {
this(model); //this(): 생성자. Car(model);과 같은 의미
System.out.println("생성자 Car(String model) 호출합니다.");
this.color = color;
}
public Car(String model, String color, String speed) {
this(model, color); // 2개짜리 생성자 호출(생성자 오버로딩)
System.out.println("생성자 Car(String model, String color)를 호출합니다.");
this.speed = speed;
this.id = ++number; //model, color, speed 모두 입력받은 경우에만 number 증가
start();
}
public Car() {
}
//메소드
public void start() {
System.out.println("완성했습니다.");
}
}
public class Static02 {
public static void main(String[] args) {
Car car1 = new Car("K5", "흰색", "159");
System.out.println("==============================");
Car car2 = new Car("K9", "검색");
System.out.println("==============================");
Car car3 = new Car("K3");
System.out.println("==============================");
Car car4 = new Car();
System.out.println("==============================");
Car car5 = new Car("K3", "빨간색", "159");
System.out.println("==============================");
Car car6 = new Car("K9", "녹색", "159");
System.out.println("==============================");
System.out.println(Car.number);
}
}
출력결과
this(1개짜리) 호출합니다.
Car(2개짜리)를 호출합니다.
완성했습니다.
==============================
this(1개짜리) 호출합니다.
==============================
==============================
==============================
this(1개짜리) 호출합니다.
Car(2개짜리)를 호출합니다.
완성했습니다.
==============================
this(1개짜리) 호출합니다.
Car(2개짜리)를 호출합니다.
완성했습니다.
==============================
3
'BackEnd > Java' 카테고리의 다른 글
[Java] java.util.comparator, java.util.comparable (0) | 2022.03.16 |
---|---|
[Java] 메소드 (0) | 2021.08.23 |
[Java] next() 와 nextLine()의 차이와 주의점 (0) | 2021.08.23 |
[Java] DBeaver 이클립스에 연결하기 (0) | 2021.08.17 |
[Java] 웹 디자인 프로그램 Oven, adobe XD (0) | 2021.08.11 |
댓글