Inheritance

Defining a Base Class 定义一个基类

Any class that does not inherit from another class is known as a base class. 一个不从任何类继承的类就是基类

// Inheritance
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()
println("Vehicle: \(someVehicle.description)")

class Bicycle: Vehicle {
    var hasBasket = false
}

let bicycle = Bicycle()
bicycle.hasBasket = true
bicycle.currentSpeed = 15.0
println("Bicycle: \(bicycle.description)")

class Tandem: Bicycle {
    var currentNumberOfPassengers = 0
}

let tandem = Tandem()
tandem.hasBasket = false
tandem.currentNumberOfPassengers = 2
tandem.currentSpeed = 22.0
println("Tandem: \(tandem.description)")

Overriding 重写

To override a characteristic that would otherwise be inherited, you prefix your overriding definition with override keyword. 为了重写而不是集成一个特征,必须要在重写的定义前加上override关键字

Accessing Superclass Methods, Properties, and Subscripts 访问父类的方法、属性和subscripts

You access the superclass version of a method, property, or subscript by using the super prefix. 通过super前缀来访问父类的巴拉巴拉

例如 super.someMethod()

super.someProperty

super[someIndex]

Overriding Methods 重写函数

You can override an inherited instance or class method to provide a tailored or alternative implementation of the method within your subclass. 

// Overriding
class Train: Vehicle {
    override func makeNoise() {
        println("Choo Choo")
    }
}
Overriding Properties 重写属性

You can override an inherited instance or class property to provide your own custom getter and setter for that property, or to add property observers to enable the overriding property to observe when the underlying property value changes. 你可以重写继承的对象或类的属性来提供你自己的定制的getter和setter方法,或者为已经有的属性添加observer来监察值的变化

// Overriding Property Getters and 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
println("Car: \(car.description)")
Overriding Property Observers

class AutomaticCar: Car {
    override var currentSpeed: Double {
        didSet {
            gear = Int(currentSpeed / 10.0) + 1
        }
    }
}

let automatic = AutomaticCar()
automatic.currentSpeed = 35.0
println("AutomaticCar: \(automatic.description)")

Preventing Overrides 避免重写

利用final关键字,如

final fund, final class func, final script, final class

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值