Swift学习这十七:重载(override)

创建一个基类:Vehicle.swift

import Foundation

//
// @brief 定义一个超类(车)
//
class Vehicle {
    var numberOfWheels: Int
    var maxPassengers: Int
    
    // designated initializer
    init() {
        numberOfWheels = 0
        maxPassengers = 2
        println("call vehicle designated initializer")
        self.nothingToDo()
    }
    
    func description() {
        println("Vehicle has (\numberOfWheels) wheels and can hold \(maxPassengers) passengers at most")
    }
    
    // 使用@final防止被重写
    @final func nothingToDo() {
        println("call nothingToDo() and it is used @final to avoid overriding")
    }
}

再创建一个子类Bicycle.swift:

import Foundation

//
// @brief 定义自行车类
//
class Bicycle : Vehicle {
    // override property
    override var numberOfWheels: Int {
        get { // 重写属性,调用super.propertyName
            println("overried property getter numberOfWheels")
            return super.numberOfWheels
        }
        set {
            println("overried property setter numberOfWheels")
            super.numberOfWheels = max(newValue, 40)
        }
    }
    
    // initializer 默认是不会被继承的
    init() {
        super.init() // initialize super class first
        println("called designated initializer")
        numberOfWheels = 2
    }
    
    // 重写方法
    override func description() {
       super.description()
        
        println("func description() was called in Bicycle")
    }
    
//    // 不能重写
//    override func nothingToDo() {
//        
//    }
}


在main.swift中测试:

import Foundation

let bicycle = Bicycle()

bicycle.numberOfWheels = 4
println(bicycle.numberOfWheels)
bicycle.maxPassengers = 84
println(bicycle.maxPassengers)
bicycle.description()

// 测试结果数据:

call vehicle designated initializer
call nothingToDo() and it is used @final to avoid overriding
called designated initializer
overried property setter numberOfWheels
overried property setter numberOfWheels
overried property getter numberOfWheels
40
84
Vehicle has (
umberOfWheels) wheels and can hold 84 passengers at most
func description() was called in Bicycle
Program ended with exit code: 0



上一篇:微信支付遇到的坑


下一篇:拉卡拉如何完成上亿用户的咨询工作?