226k views
3 votes
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 isAntique 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.

1 Answer

3 votes

Answer:

Java Code example

Step-by-step explanation:

Java Code

import java.util.Calendar;

public class CarTest {

public static void main(String [] args){

Car car1 = new Car("Honda","Civic", 2015);

System.out.println(car1.toString());

System.out.println("Car 1 is antique : "+car1.isAntique());

Car car2 = new Car("Toyota","A", 1945);

System.out.println(car2.toString());

System.out.println("Car 2 is antique : "+car2.isAntique());

Car car3 = new Car("Lamborghini","Model A", 2019);

System.out.println(car3.toString());

System.out.println("Car 3 is antique : "+car3.isAntique());

}

}

class Car{

private String model;

private String make;

private int year;

public Car( String make,String model, int year) {

this.model = model;

this.make = make;

this.year = year;

}

public String getModel() {

return model;

}

public void setModel(String model) {

this.model = model;

}

public String getMake() {

return make;

}

public void setMake(String make) {

this.make = make;

}

public int getYear() {

return year;

}

public void setYear(int year) {

this.year = year;

}

public boolean isAntique(){

return Calendar.getInstance().get(Calendar.YEAR)-year>45;

}

@Override

public String toString() {

return "Car{" +

"model='" + model + '\'' +

", make='" + make + '\'' +

", year=" + year +

'}';

}

}

Code Explanation

Declaring the instance variable and initializing those in constructor. Defining there getter setter and create a toString method, toString method will return the overall object representation.

To check whether car is antique or not, we will use java.util.Calendar class, This class will return the current date year from which we can compare the car year to check whether the car is antique or not.

Output

Output of above TestCar is given below.

__________________________________

Car{model='Civic', make='Honda', year=2015}

Car 1 is antique : false

Car{model='A', make='Toyota', year=1945}

Car 2 is antique : true

Car{model='Model A', make='Lamborghini', year=2019}

Car 3 is antique : false

User Jiaqi
by
7.7k points