CarDemo
3369 ワード
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("
Current 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("
Accelerating 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("
Decelerating four wheel drive car...");
fwdCar.brake();
fwdCar.brake();
// Decelerate the sports car three times
System.out.println("
Decelerating sports car...");
sportsCar.brake();
sportsCar.brake();
sportsCar.brake();
// Accelerate the sports car two times
System.out.println("
Accelerating sports car...");
sportsCar.accelerate();
sportsCar.accelerate();
// Display the speed of the sports car
System.out.println("
Now 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