定义基类
class Vehicle { var currentSpeed = 0.0 var description: String { return "traveling at \(currentSpeed) miles per hour" } func makeNoise() { // 什么也不做-因为车辆不一定会有噪音 } } let someVehicle = Vehicle() print("Vehicle: \(someVehicle.description)") // Vehicle: traveling at 0.0 miles per hour
子类生成
class Bicycle: Vehicle { var hasBasket = false } let bicycle = Bicycle() bicycle.hasBasket = true bicycle.currentSpeed = 15.0 print("Bicycle: \(bicycle.description)") // Bicycle: traveling at 15.0 miles per hour
class Tandem: Bicycle { var currentNumberOfPassengers = 0 } let tandem = Tandem() tandem.hasBasket = true tandem.currentNumberOfPassengers = 2 tandem.currentSpeed = 22.0 print("Tandem: \(tandem.description)") // Tandem: traveling at 22.0 miles per hour
重写
或下标脚本(subscript)提供自己定制的实现(implementation)。我们把这种行为叫重写(overriding)。
重写方法
class Train: Vehicle { override func makeNoise() { print("Choo Choo") } } let train = Train() train.makeNoise() // prints "Choo Choo"
重写属性
你可以将一个继承来的只读属性重写为一个读写属性,只需要你在重写版本的属性里提供 getter 和 setter 即可。
class Car: Vehicle { var gear = 1 override var description: String { return super.description + " in gear \(gear)" } } let car = Car() car.currentSpeed = 25.0 car.gear = 3 print("Car: \(car.description)") // Car: traveling at 25.0 miles per hour in gear 3
重写属性观察器
class AutomaticCar: Car { override var currentSpeed: Double { didSet { gear = Int(currentSpeed / 10.0) + 1 } } } let automatic = AutomaticCar() automatic.currentSpeed = 35.0 print("AutomaticCar: \(automatic.description)") // AutomaticCar: traveling at 35.0 miles per hour in gear 4
防止重写
在扩展中,你添加到类里的方法,属性或下标脚本也可以在扩展的定义里标记为 final。
你可以通过在关键字class前添加final特性(final class)来将整个类标记为 final 的,这样的类是不可被继承的,否则会报编译错误。
你可以通过在关键字class前添加final特性(final class)来将整个类标记为 final 的,这样的类是不可被继承的,否则会报编译错误。