閱讀891 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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



最後更新:2017-04-03 07:57:00

  上一篇:go [推薦係統]互聯網推薦係統比較研究
  下一篇:go Aix 命令小記