Skip to content

Car Rentals

  • Project
  • 1 hint
  • 4 of 6 in this chapter

Context

For this project, you will develop a program that provides information useful to people looking to rent a car. You are a car rental sales person and your job is to provide details about all of the cars on the lot.

Task

You will need to write a class for the general concept of a Car.

This class should have the basic feature of all cars: 4 wheels.

The other essential features cost and year should be passed through the init() method. Then, you should create child classes for two general types of cars, the sedan and the coupe. As we know, coupes typically have 2 seats, whereas sedans have 5.

So put this info into the classes with variable seats.

Then, add a description function to the child classes that provide a description of the car using all the available info: wheels, seats, cost, and year. Finally, create 4 cars of your liking using these child classes, and print out their descriptions to the console using a for loop and array! Have fun!

Hints

Hint 1hint 1

hint 2

Solution

Swift
class Car {
 let wheels = 4
 var cost: Double
 var year: Int
 init(cost: Double, year: Int) {
 self.cost = cost
 self.year = year
 }
 func description() {
 print("I have \(wheels) wheels!")
 }
}
class Coupe: Car {
 var seats = 2
 override init(cost: Double, year: Int) {
 super.init(cost: cost, year: year)
 }
 override func description() {
 print("I have \(wheels) wheels and \(seats) seats. I cost $\(cost) per day and am from \(year)!")
 }
}
class Sedan: Car {
 var seats = 4
 override init(cost: Double, year: Int) {
 super.init(cost: cost, year: year)
 }
 override func description() {
 print("I have \(wheels) wheels and \(seats) seats. I cost $\(cost) per day and am from \(year)!")
 }
}
let civiccoupe = Coupe(cost: 50.00, year: 2019)
let mercsedan = Sedan(cost: 70.00, year: 2014)
let bmw3series = Sedan(cost: 80.00, year: 2019)
let ferrari = Coupe(cost: 500.00, year: 2011)
let cars = [civiccoupe, mercsedan, bmw3series, ferrari]

for car in cars {
 car.description()
}

Give the project a try first.