본문 바로가기

Java/과제

chapter06) 클래스 example - Car

아래의 클래스 다이어그램에 해당하는 Car 클래스를 만들고, 테스트 코드로 Car 클래스를 테스트 해 보자.

package practice;

public class Car {
	// 필드
	private double speed;
	private String color;
	private static final double MAX_SPEED = 200.0;
	
	// 생성자
	public Car() {

	}

	public Car(String color) {
		this.color = color;
	}

	// 메소드
	public double getSpeed() {
		return speed;
	}

	public void setSpeed(double speed) {
		this.speed = speed;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public boolean speedUp(double speed) {
		if (speed + this.speed < 0 || speed + this.speed > MAX_SPEED) {
			return false;
		}
		this.speed += speed;
		return true;
	}
	public static double getMaxSpeed() {
		return MAX_SPEED;
	}
}

 

package practice;

public class CarTest {
	public static void main(String[] args) {
		Car myCar = new Car("red");
		System.out.println("myCar의 색: " + myCar.getColor());
		System.out.println("차의 최대 속력: " + Car.getMaxSpeed() + "㎞/h");

		System.out.print("첫 번째 speedUp(100.0㎞/h): ");
		if (myCar.speedUp(100.0)) {
			System.out.print("속도 변경 가능,");
		} else {
			System.out.print("속도 변경 불가능,");
		}
		System.out.println(" 현재 차의 속력: " + myCar.getSpeed() + "㎞/h");

		System.out.print("두 번째 speedUp(90.0㎞/h): ");
		if (myCar.speedUp(90.0)) {
			System.out.print("속도 변경 가능,");
		} else {
			System.out.print("속도 변경 불가능,");
		}
		System.out.print(" 현재 차의 속력: " + myCar.getSpeed() + "㎞/h");

		Car yourCar = new Car("blue");
		System.out.println();
		System.out.println("yourCar의 색: " + yourCar.getColor());
		System.out.println("차의 최대 속력: " + Car.getMaxSpeed() + "㎞/h");

		System.out.print("첫 번째 speedUp(-100.0㎞/h): ");
		if (yourCar.speedUp(-100.0)) {
			System.out.print("속도 변경 가능, ");
		} else {
			System.out.print("속도 변경 불가능, ");
		}
		System.out.println(" 현재 차의 속력: " + yourCar.getSpeed() + "㎞/h");

		System.out.print("두 번째 speedUp(210.0㎞/h): ");
		if (yourCar.speedUp(210.0)) {
			System.out.print("속도 변경 가능, ");
		} else {
			System.out.print("속도 변경 불가능, ");
		}
		System.out.print(" 현재 차의 속력: " + yourCar.getSpeed() + "㎞/h");
	}
}

Recent Posts
Popular Posts
Tags
더보기
Recent Comments