继承(Inheritance)
1.基类
- 基类是不继承其他任何类的类;
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
}
}
2.子类
子类化语法格式:
class SomeSubclass: SomeSuperclass {
// subclass definition goes here
}
class Bicycle: Vehicle {
var hasBasket = false
}
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
3.重写
在Swift中,使用关键字override
表明在子类中重写了父类的方法,属性或下标。
(1).访问父类的方法,属性,下标
- 当在子类中需要访问父类的方法,属性,下标时,用关键字
super
来访问。
(2).重写方法
class Train: Vehicle {
override func makeNoise() {
print("Choo Choo")
}
}
let train = Train()
train.makeNoise()
(3)重写属性的Getters 和 Setters方法
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
(4).重写属性的监听者
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
3.防止重写
将父类的方法,属性,下标标记为final
来防止被子类重写。