253,667 views
12 votes
12 votes
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 Ksav
by
2.6k points

1 Answer

24 votes
24 votes

Answer:

Here is an example of a class called Car that includes three instance variables: model (type String), year (type String), and price (double). The class includes a constructor that initializes the three instance variables, as well as set and get methods for each instance variable:

Car.java:

public class Car {

private String model;

private String year;

private double price;

// Constructor

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

this.model = model;

this.year = year;

if (price > 0) {

this.price = price;

}

}

// Set methods

public void setModel(String model) {

this.model = model;

}

public void setYear(String year) {

this.year = year;

}

public void setPrice(double price) {

if (price > 0) {

this.price = price;

}

}

// Get methods

public String getModel() {

return model;

}

public String getYear() {

return year;

}

public double getPrice() {

return price;

}

}

Here is an example of a test application named CarApplication that demonstrates the capabilities of the Car class:

CarApplication.Java:

public class CarApplication {

public static void main(String[] args) {

Car car1 = new Car("Ford", "2020", 30000.0);

Car car2 = new Car("Toyota", "2019", 35000.0);

// Display the price of each car

System.out.println("Car 1: " + car1.getPrice());

System.out.println("Car 2: " + car2.getPrice());

// Apply a 5% discount on the price of car 1

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

// Apply a 7% discount on the price of car 2

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

// Display the price of each car again

System.out.println("Car 1: " + car1.getPrice());

System.out.println("Car 2: " + car2.getPrice());

}

}

Step-by-step explanation:

When this code is run, it will output the following:

Car 1: 30000.0

Car 2: 35000.0

Car 1: 28500.0

Car 2: 32850.0

User SimpleSi
by
2.7k points