메서드를 private으로 만들기
Private 메서드는 로직을 더 작고 재사용 가능한 메서드로 캡슐화해 코드의 모듈성을 높이는 데에도 사용돼요. 이번에는 Car 클래스에 에어백을 전개하는 메서드를 추가하겠습니다. 보안상 이 메서드는 외부에서 접근할 수 없도록 하는 편이 좋아요.
이 연습은 강의의 일부입니다
Java로 배우는 객체 지향 프로그래밍 입문
연습 안내
- 매개변수가 없고 반환 타입이
void인private메서드deployAirbags를 만드세요. deployAirbags메서드 안에서"airbags deployed"메시지를 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
public class Main {
static class Car {
public String color;
public String model;
public int year;
private int vehicleNumber;
public Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
this.vehicleNumber = 101189;
}
// Create deployAirbags method
____ ____ deployAirbags() {
System.out.println("____");
}
public void turnEngineOn() {
System.out.println("engine is on");
}
public int calculateMPG(int milesDriven, int gallonsUsed) {
return milesDriven / gallonsUsed;
}
}
public static void main(String[] args) {
Car myCar = new Car("red", "camry", 2022);
}
}