Car 클래스에 생성자 만들기
클래스의 속성에 값을 설정할 수 있어야 효과적으로 사용할 수 있어요. 지금부터 Car 클래스에 생성자를 만들고, 그 속성들이 어떤 값으로든 설정되도록 해 보겠습니다.
기억하세요: 클래스의 생성자는 인스턴스를 만들 때 항상 호출됩니다.
이 연습은 강의의 일부입니다
Java로 배우는 객체 지향 프로그래밍 입문
연습 안내
- 매개변수가 없는
Car클래스의 생성자 메서드를 만드세요. - 생성자 내부에서
color속성을 문자열"red"로 설정하세요. - 생성자 내부에서
year를 정수2019로 설정하세요. myCar객체 인스턴스의color속성을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
class Main {
static class Car {
String color;
String model;
int year;
// Create constructor method
____() {
this.model = "camry";
// Assign the values for the color and year properties
____.____ = "____";
____.____ = ____;
}
}
public static void main(String[] args) {
Car myCar = new Car();
// Print the "color" property
System.out.println(____.____);
}
}