In: Computer Science
Car Class
Write a class named Car that has the following member
variables:
• year. An int that holds the car’s model year.
• make. A string object that holds the make of the car.
• speed. An int that holds the car’s current speed. In addition,
the class should have the following member functions.
• Constructor. The constructor should accept the car’s year and
make as arguments and assign these values to the object’s year and
make member variables. The constructor should initialize the speed
member variable to 0.
• Accessors. Appropriate accessor functions should be created to
allow values to be retrieved from an object’s year, make, and speed
member variables.
• accelerate. The accelerate function should add 5 to the speed
member variable each time it is called.
• brake. The brake function should subtract 5 from the speed member
variable each time it is called.
Demonstrate the class in a program that creates a Car object, and then calls the accelerate function five times. After each call to the accelerate function, get the current speed of the car and display it. Then, call the brake function five times. After each call to the brake function, get the current speed of the car and display it.
Mimir Requirement: The file name must be: Homework6A.cpp
Test Case:
1967 Ford Mustang - current speed : 5
1967 Ford Mustang - current speed : 10
1967 Ford Mustang - current speed : 15
1967 Ford Mustang - current speed : 20
1967 Ford Mustang - current speed : 25
1967 Ford Mustang - current speed : 20
1967 Ford Mustang - current speed : 15
1967 Ford Mustang - current speed : 10
1967 Ford Mustang - current speed : 5
1967 Ford Mustang - current speed : 0
Code
public class Car{
// member variables
private String make;
private int year,speed;
// constructor
public Car(String mak,int y){
make = mak;
year = y;
speed = 0;
}
// accessor to access values
public String getMake(){
return make;
}
public int getYear(){
return year;
}
public int getSpeed(){
return speed;
}
// accelerate function
public void accelerate(){
speed = speed + 5; // add 5 to speed
}
// brake function
public void brake(){
speed = speed - 5; // subtract 5 from speed
}
public static void main(String []args){
// create a car object
Car car = new Car("Ford Mustang",1967);
// call accelerate 5 times and show details
for(int i=0;i<5;i++){
car.accelerate();
System.out.println(car.getYear()+" "+car.getMake()+" - current speed : "+car.getSpeed());
}
// call brake 5 times
for(int i=0;i<5;i++){
car.brake();
System.out.println(car.getYear()+" "+car.getMake()+" - current speed : "+car.getSpeed());
}
}
}
Code screenshot:
Code output:
=========================
The code for the class Car along with methods mentioned have been implemented above. Comments have been added to help you understand.