가장 쉽게 설명하는 Swift, 김창만, 루비페이퍼, 10장 상속 코드부분
class Vehicle {
var numberOfWheels: Int
var maxPassengers: Int
func description() -> String {
return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers"
}
init() {
numberOfWheels = 0
maxPassengers = 1
}
}
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
class Tandem: Bicycle {
override init() {
super.init()
maxPassengers = 2
}
}
let myVehicle = Vehicle()
let myBicycle = Bicycle()
let myTandem = Tandem()
print("[myVehicle]: \(myVehicle.description())")
print("[myBicycle]: \(myBicycle.description())")
print("[myTandem]: \(myTandem.description())")
class Car: Vehicle {
var speed = 0.0
override init() {
super.init()
maxPassengers = 5
numberOfWheels = 4
}
override func description() -> String {
return super.description() + "; " + "travelling at \(speed) mph"
}
}
let myCar = Car()
print("[myCar] \(myCar.description())")
class SpeedLimitedCar: Car {
override var speed: Double {
get {
return super.speed
}
set {
super.speed = min(newValue, 40.0)
}
}
}
let myLimitedCar = SpeedLimitedCar()
myLimitedCar.speed = 60.0
print("[myLimitedCar]: \(myLimitedCar.description())")