Create a class named Car that has the following attributes: year model (car\'s y
ID: 3811928 • Letter: C
Question
Create a class named Car that has the following attributes: year model (car's year model) make (car's make) speed (car's current speed) It should also have the following methods: accelerate: adds 5 to the speed data attribute brake: subtract 5 from the speed of the car gets_peed: return the current speed Use this class to create an instance of the car class by getting the car year, make, and current speed from user information. The program should then accelerate the car once. If your program is correct, sample output might look as follows: Please the car's year: 2005 Please the car's make: Corolla Please the car's current speed in mph: 60 Now the 2005 Corolla is going 65 mph.Explanation / Answer
Car.java
public class Car {
//Declaring instance variables
private int year_model;
private String make;
private int speed;
//Parameterized constructor
public Car(int year_model, String make, int speed) {
super();
this.year_model = year_model;
this.make = make;
this.speed = speed;
}
//This method will increase the speed of the car by 5 mph
public void accelerate()
{
speed+=5;
}
//This method will decrease the speed of the car by 5 mph
public void brake()
{
speed-=5;
}
//Getting the speed of the car
public int getSpeed() {
return speed;
}
//Display the contents of the Car class object
@Override
public String toString() {
return "Now the "+year_model+" "+make+" is going "+getSpeed()+" mph.";
}
}
__________________
Driver.java
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
//Declaring variables
int year,speed;
String make;
//Scanner object is used to get the inputs entered by the user
Scanner sc=new Scanner(System.in);
//getting the car class info
System.out.print("Enter the Car's Year :");
year=sc.nextInt();
System.out.print("Enter the car's make :");
make=sc.next();
System.out.print("Enter the car's current speed in mph :");
speed=sc.nextInt();
/* Creating the Car class object by passing
* the user entered inputs as arguements
*/
Car c=new Car(year, make, speed);
//calling the accelerate method on the car class object
c.accelerate();
System.out.println(c.toString());
System.out.print("");
}
}
______________________
Output:
Enter the Car's Year :2005
Enter the car's make :Corolla
Enter the car's current speed in mph :60
Now the 2005 Corolla is going 65 mph.
_______________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.