class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
// do nothing - an arbitrary vehicle doesn't necessarily make a noise
}
}
let someVehicle = Vehicle()
print("Vehicle: \(someVehicle.description)")
// Vehicle: traveling at 0.0 miles per hour
子類
class SomeSubclass: SomeSuperclass {
// subclass definition goes here
}
//eg:
class Bicycle: Vehicle {
var hasBasket = false
}
//useing
let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
print("Bicycle: \(bicycle.description)")
// Bicycle: traveling at 15.0 miles per hour
//eg:
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
//useing
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
重寫(override)
子類可以提供它自己的實(shí)例方法旗芬、類型方法舌胶、實(shí)例屬性,類型屬性或下標(biāo)腳本的自定義實(shí)現(xiàn)疮丛,否則它將會(huì)從父類繼承幔嫂。這就所謂的重寫。
要重寫而不是繼承一個(gè)特征誊薄,你需要在你的重寫定義前面加上 override 關(guān)鍵字履恩。這樣做說(shuō)明你打算提供一個(gè)重寫而不是意外提供了一個(gè)相同定義。意外的重寫可能導(dǎo)致意想不到的行為呢蔫,并且任何沒(méi)有使用 override 關(guān)鍵字的重寫都會(huì)在編譯時(shí)被診斷為錯(cuò)誤切心。
override 關(guān)鍵字會(huì)執(zhí)行 Swift 編譯器檢查你重寫的類的父類(或者父類的父類)是否有與之匹配的聲明來(lái)供你重寫。這個(gè)檢查確保你重寫的定義是正確的片吊。
重寫方法
//eg
class Train: Vehicle {
override func makeNoise() {
print("Choo Choo")
}
}
//useing
let train = Train()
train.makeNoise()
// prints "Choo Choo"
重寫屬性
//eg
class Car: Vehicle {
var gear = 1
override var description: String {
return super.description + " in gear \(gear)"
}
}
//useing
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
重寫屬性觀察器
//eg
class AutomaticCar: Car {
override var currentSpeed: Double {
didSet {
gear = Int(currentSpeed / 10.0) + 1
}
}
}
// useing
let automatic = AutomaticCar()
automatic.currentSpeed = 35.0
print("AutomaticCar: \(automatic.description)")
// AutomaticCar: traveling at 35.0 miles per hour in gear 4
阻止重寫(final)
final var 绽昏, final func , final class func 俏脊, fianl subscript