Design a class named Car that has the following fields:

yearModel: an int instance variable that holds the car’s year model.
make: a string instance variable that holds the make of the car.
speed: an int instance variable that holds the car’s current speed.
In addition, the class should have the following methods.

Constructor 1: no-arg constructor set the yearModel, make and speed to 2000, Nissan and 4, respectively.
Constructor 2: this is an overloaded constructor. This constructor should accept the car’s year model, speed, and make as arguments. These values should be assigned to the object’s yearModel, speed and make fields.
Accessor (getters): appropriate accessor methods to get the values stored in an object’s yearModel, make, and speed fields.
Mutator (setters): appropriate mutator methods to store values in an object’s yearModel, make, and speed fields.
toString: returns a string describing the object’s yearModel, make and speed.

Respuesta :

Answer:

// The class car is defined

public  class Car {

  // instance variable yearModel

  private int yearModel;

  // instance variable make

  private String make;

  // instance variable speed

  private int speed;

 

  // empty constructor

  // with instances inside it

  // the instances are from the question

  public Car(){

      yearModel = 2000;

      make = "Nissan";

      speed = 4;

  }  

  // overloaded constructor

  // constructor defined with three arguments

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

      // the arguments are assigned to the object's variable

      this.yearModel = yearModel;

      this.make = make;

      this.speed =speed;

  }

  // setter(mutator) method

  public void setYearModel(int yearModel){

      this.yearModel = yearModel;

  }

  // setter(mutator) method

  public void setMake(String make){

      this.make = make;

  }

  // setter(mutator) method

  public void setSpeed(int speed){

      this.speed = speed;

  }

  // getter(accessor) method

  public int getYearModel(){

      return yearModel;

   }

  // getter(accessor) method

  public String getMake(){

      return make;

   }

  // getter(accessor) method

  public int getSpeed(){

      return speed;

   }  

  // toString is override to display the car object properties

  public String toString(){

      return "Car's year model: " + getYearModel() + ", make: " + getMake() + ", speed: " + getSpeed();

  }

}

Explanation:

The code is well commented.

ACCESS MORE