116k views
5 votes
Write a class named Car that has the following member variables: - yearModel. An int that holds the car’s year model. - make. A string that holds the make of the car. - speed. An int that holds the car’s current speed. The class should have the following member functions: - Appropriate accessor functions to get the values stored in an object’s yearModel, make, and speed member variables. - accelerate function that adds 5 to the speed member variable each time it is called. - brake function that subtracts 5 from the speed member variable each time it is called.

User Gen Wan
by
7.6k points

1 Answer

2 votes

Answer:

public class Car {

//Member variables

private int yearModel;

private String make;

private int speed;

//Constructor

public Car(int yearModel, String make, int speed) {

this.yearModel = yearModel;

this.make = make;

this.speed = speed;

}

//Accessor Methods getters and setters

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;

}

//Accelerate function

public void accelerate(){

this.speed+=5;

}

// Brake function

public void brake(){

this.speed-=5;

}

}

Step-by-step explanation:

  • As required by the question, The class Car is created using Java programming language
  • The members variables, the constructor, The accessor methods are all created as required by the question (Please pay attention to the comments added to the code)
  • The accelerate and brake functions that add and subtract 5 from the speed member variable respectively are also created.
User Murthy Pidugu
by
8.3k points