생성자 오버로딩
생성자도 다른 메서드와 같기 때문에 다형성으로 오버로딩할 수 있습니다. Tesla 클래스에 자동차의 보험 가입 여부를 받는 두 번째 생성자를 추가해, 서로 다른 생성자를 통해 Tesla 클래스의 객체 인스턴스를 여러 개 만들 수 있도록 수정해 보세요.
이 연습은 강의의 일부입니다
Java로 배우는 객체 지향 프로그래밍 입문
연습 안내
Tesla클래스의 두 번째 생성자 메서드를 완성해 추가 매개변수booleanisInsured를 받도록 하세요.- 새로운
Tesla생성자 메서드 내부에서, 생성자 매개변수에 맞게isInsured클래스 속성을 설정하세요. - 새로운 생성자 메서드를 사용해
Tesla클래스의 두 번째 객체 인스턴스mySecondTesla를 생성하고, 매개변수 값으로"modelY","black",false를 전달하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
public class Main {
static class Tesla {
public String model;
public String color;
public boolean isInsured;
public Tesla(String model, String color){
this.model = model;
this.color = color;
}
// Complete second constructor
public ____(String model, String color, ____ ____){
this.model = model;
this.color = color;
// Set the isInsured property
____.____ = ____;
}
}
public static void main(String[] args) {
Tesla myFirstTesla = new Tesla("modelX", "red");
// Create object instance with second constructor
____ mySecondTesla = new ____("____", "black", ____);
}
}