172k views
1 vote
Create a class called Car that includes three instance variables—a model (type

String), a year (type String), and a price (double). Provide a constructor that initializes the three
instance variables. Provide a set and a get method for each instance variable. If the price is not positive,
do not set its value. Write a test application named CarApplication that demonstrates class Car’s capabilities. Create two Car objects and display each object’s price. Then apply a 5% discount on the
price of the first car and a 7% discount on the price of the second. Display each Car’s price again.

User IMickyRich
by
3.9k points

1 Answer

4 votes

Answer:

Here is the implementation of the Car class:

class Car {

private String model;

private String year;

private double price;

public Car(String model, String year, double price) {

this.model = model;

this.year = year;

if (price > 0) {

this.price = price;

}

}

public String getModel() {

return model;

}

public void setModel(String model) {

this.model = model;

}

public String getYear() {

return year;

}

public void setYear(String year) {

this.year = year;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

if (price > 0) {

this.price = price;

}

}

}

Here is the test application that demonstrates the capabilities of the Car class:

class CarApplication {

public static void main(String[] args) {

Car car1 = new Car("Toyota", "2020", 20000);

Car car2 = new Car("Honda", "2019", 25000);

System.out.println("Original price of car1: $" + car1.getPrice());

System.out.println("Original price of car2: $" + car2.getPrice());

car1.setPrice(car1.getPrice() * 0.95);

car2.setPrice(car2.getPrice() * 0.93);

System.out.println("Discounted price of car1: $" + car1.getPrice());

System.out.println("Discounted price of car2: $" + car2.getPrice());

}

}

User WhiteHorse
by
3.7k points