class Person { var name: String var age: Int func description() -> String { return "\(name) 年齡是: \(age)" } convenience init () { self.init(name: "Tony") self.age = 18 } convenience init (name: String) { self.init(name: name, age: 18) } init (name: String, age: Int){ self.name = name self.age = age } } class Student: Person { var school: String init (name: String, age: Int,school: String) { self.school = school super.init(name: name, age: age) } convenience overrideinit (name: String,age: Int) { self.init(name: name, age: age, school: "清華大學") } } class Graduate: Student { var special: String = "" }
來看看符合條件1的繼承,Graduate繼承Student,Graduate類沒有定義任何指定構造函數,它將自動繼承所有Student的指定構造函數。符合條件1後,Graduate從Student繼承了如下指定構造函數:
init (name : String, age : Int,school : String)
再看符合條件2的繼承,由於Graduate實現了Student的所有指定構造函數,Graduate將自動繼承所有Student的便利構造函數。符合條件2後,Graduate從Student繼承了如下3個便利構造函數:
init (name: String, age: Int) init (name: String) init ()