Write a class called Car that contains instance data that represents the make, m
ID: 3670515 • Letter: W
Question
Write a class called Car that contains instance data that represents the make, model, and year of the car. Define the Car constructor to initialize these values. Include getter and setter methods for all instance data, and a toString method that returns a one – line description of the car. Add a method called 1 sAnt 1 que that returns a Boolean indicating if the car is an antique (if it is more than 45 years old). Create a driver class called CarTest, whose main method instantiates and updates several Car objects.
Explanation / Answer
Car.java
public class Car
{
String make, model;
int year;
public Car(String a, String b, int c)
{
// initialise instance variables
make = a;
model = b;
year = c;
}
public void setMake(String a)
{
make = a;
}
public void setModel(String b)
{
model = b;
}
public void setYear(int c)
{
year = c;
}
public String getMake()
{
return make;
}
public String getModel()
{
return model;
}
public int getYear()
{
return year;
}
public boolean isAntique(int c)
{
if (2015-year > 45)
return true;
else
return false;
}
public String toString()
{
return "The make of the car is " + make + " and the model is " + model + " and the year is " + year;
}
}
CarRunner.java
import java.util.Scanner;
public class CarRunner
{
public static void main (String[] args)
{
String a, a2, b, b2;
int c, c2;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the make of the car:");
a = scan.nextLine();
System.out.println("Enter the model of the car:");
b = scan.nextLine();
System.out.println("Enter the year of the car:");
c = scan.nextInt();
Car car1 = new Car(a, b, c);
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter the make of the car:");
a2 = scan2.nextLine();
System.out.println("Enter the model of the car:");
b2 = scan2.nextLine();
System.out.println("Enter the year of the car:");
c2 = scan2.nextInt();
Car car2 = new Car(a2, b2, c2);
System.out.println(car1.getMake() + " " + car1.getModel() + " " + car1.getYear());
System.out.println(car1.isAntique(c));
System.out.println(car2);
System.out.println(car2.isAntique(c));
}
}
output
Enter the make of the car:
Ram
Enter the model of the car:
spaceflyer
Enter the year of the car:
1996
Enter the make of the car:
Sai
Enter the model of the car:
maruthi
Enter the year of the car:
1995
Ram spaceflyer 1996
false
The make of the car is Sai and the model is maruthi and the year is 1995
false
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.