Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Classes Assignment - Class Write a class named Car that has the following member

ID: 3729754 • Letter: C

Question

Classes Assignment - 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 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. A fter 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.

Explanation / Answer

class Car
{
private int yearModel;
private String make;
private int speed;
public Car(int yearModel,String make)   //constructor
{
  this.yearModel = yearModel;
  this.make = make;
  this.speed = 0;                     //speed = 0
}
public int getYearModel() //accessor and mutator methods
{
  return yearModel;
}
public String getMake()
{
  return make;
}
public void setMake(String make)
{
  this.make = make;
}
public int getSpeed()
{
  return speed;
}
public void accelerate()
{
  speed = speed +5;             //speed is increased by 5
}
public void brake()
{
  speed = speed -5;                //speed is decreased by 5
}




}
class TestCar
{
    public static void main (String[] args)
    {
     Car car = new Car(2011,"Hyundai");
    
     System.out.println("Car Model Year : "+car.getYearModel()+" Make: "+car.getMake());
    
     System.out.println("Accelerating........");   //calling accelerate() 5 times
    
     for(int i=1;i<=5;i++)
     {
     car.accelerate();
     System.out.println("Speed : "+car.getSpeed());
     }
    
    
     System.out.println("Braking..............");   //calling brake 5 times
    
     for(int i=1;i<=5;i++)
     {
     car.brake();
     System.out.println("Speed : "+car.getSpeed());
     }
  
    }
}

output:

Car Model Year : 2011 Make: Hyundai
Accelerating........
Speed : 5
Speed : 10
Speed : 15
Speed : 20
Speed : 25
Braking..............
Speed : 20
Speed : 15
Speed : 10
Speed : 5
Speed : 0