下面看一個示例:
final class Person { //聲明為final,說明它是不能被繼承的 var name: String final var age: Int //定義的age屬性 final func description() -> String { //定義description實例方法 return "\(name) 年齡是: \(age)" } final class func printClass() ->() { //定義printClass靜態方法 print( "Person 打印...") } init (name: String, age: Int) { self.name = name self.age = age } } class Student: Person { //編譯錯誤 var school: String convenience init() { self.init(name: "Tony", age: 18, school: "清華大學") } init (name: String, age: Int, school: String) { self.school = school super.init(name: name, age: age) } override func description() -> String { //編譯錯誤 //試圖重寫description實例方法 print("父類打印 \(super.description())") return "\(name) 年齡是: \(age), 所在學校: \(school)。" } override class func printClass() ->() { //編譯錯誤 //試圖重寫printClass靜態方法 print( "Student 打印...") } override var age: Int { //編譯錯誤 //試圖重寫age屬性 get { return super.age } set { super.age = newValue < 8 ? 8: newValue } } }
定義Student類,並聲明為Person子類時,會報如下編譯錯誤: