ITeye博客

CarDemo

MrCrapBag · 2013-04-10 22:18 · 编程语言 · Markdown



public class Car
{
	// the car's year model
	private int yearModel;
	// the make of the car.
	private String make;
	// the car's current speed.
	private int speed;

	// no-arg constructor
	public Car()
	{
		yearModel = 2004;
		make = "Honda";
		speed = 0;
	}

	// constructor
	public Car(int yearModel, String make, int speed)
	{
		super();
		this.yearModel = yearModel;
		this.make = make;
		this.speed = speed;
	}

	public int getYearModel()
	{
		return yearModel;
	}

	public void setYearModel(int yearModel)
	{
		this.yearModel = yearModel;
	}

	public String getMake()
	{
		return make;
	}

	public void setMake(String make)
	{
		this.make = make;
	}

	public int getSpeed()
	{
		return speed;
	}

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

	public void accelerate()
	{
		speed += 5;
	}

	public void brake()
	{
		if (5 < speed)
		{
			speed -= 5;
		}
		else
		{
			speed = 0;

		}

	}

}


package com.test;

public class CarDemo
{

	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		Car fwdCar = new Car();
		Car sportsCar = new Car(2004, "Porsche", 100);

		// Display the current status of four wheel drive Car
		System.out.println("\nCurrent status of the sports car:");
		System.out.println("Year model: " + sportsCar.getYearModel());
		System.out.println("Make: " + sportsCar.getMake());
		System.out.println("Speed: " + sportsCar.getSpeed());

		// Accelrate the four wheel drive car five times.
		System.out.println("\nAccelerating four wheel drive drive car...");
		fwdCar.accelerate();
		fwdCar.accelerate();
		fwdCar.accelerate();
		fwdCar.accelerate();
		fwdCar.accelerate();

		// Decelerate the four wheel drive car two times.
		System.out.println("\nDecelerating four wheel drive car...");
		fwdCar.brake();
		fwdCar.brake();

		// Decelerate the sports car three times
		System.out.println("\nDecelerating sports car...");
		sportsCar.brake();
		sportsCar.brake();
		sportsCar.brake();

		// Accelerate the sports car two times
		System.out.println("\nAccelerating sports car...");
		sportsCar.accelerate();
		sportsCar.accelerate();

		// Display the speed of the sports car
		System.out.println("\nNow the speed of the sports car is "
				+ sportsCar.getSpeed());
	}

}

运行结果:

Current status of the sports car: Year model: 2004 Make: Porsche Speed: 100

Accelerating four wheel drive drive car...

Decelerating four wheel drive car...

Decelerating sports car...

Accelerating sports car...

Now the speed of the sports car is 95

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。