看下面的代码
class Person { var name: String var health:Int = 100 { didSet{ if self.health > 100 { self.health = 100 } if self.health <= 0 { self.isAlive = false } } } var isAlive:Bool = true var description: String { return "i am a person,name is \(self.name)" } init(name: String) { self.name = name } func beAttacted(health:Int) -> Void { self.health -= health } // 加上final不能被子类重写 final func getHealth() -> Int { return self.health } } func cure(person:Person) { person.health += 10 } class Solider: Person { var weapon: String? override var description: String { // 类的重载 return "i am a Solider,name is \(self.name)" } override func beAttacted(health:Int) -> Void { // 重载方法 self.health -= health/2 } } class Worker: Person { var work: String? override var description: String { // 类的重载 return "i am a Worker,name is \(self.name)" } } // final 表示不可被继承 final class Taxpayer: Worker { var taxRate:Float = 0 } var solider = Solider(name: "solider") cure(person: solider) solider.health print(solider.description) var worker = Worker(name: "worker") cure(person: worker) worker.health print(worker.description)
上面打印结果
i am a Solider,name is solider
i am a Worker,name is worker
i am a Solider,name is worker
Swift 的两段式构造
class Person { var name: String var health:Int = 100 { didSet{ if self.health > 100 { self.health = 100 } if self.health <= 0 { self.isAlive = false } } } var isAlive:Bool = true var description: String { return "i am a person,name is \(self.name)" } init(name: String) { self.name = name } func beAttacted(health:Int) -> Void { self.health -= health } // 加上final不能被子类重写 final func getHealth() -> Int { return self.health } } class Solider: Person { var weapon: String override var description: String { // 类的重载 return "i am a Solider,name is \(self.name)" } override func beAttacted(health:Int) -> Void { // 重载方法 self.health -= health/2 } init(weapon: String,name:String) { // swift两段式构造,先构造子类的元素,再构造父类的元素 self.weapon = weapon super.init(name: name) } }
class Person { var name: String var health:Int = 100 { didSet{ if self.health > 100 { self.health = 100 } if self.health <= 0 { self.isAlive = false } } } var isAlive:Bool = true var description: String { return "i am a person,name is \(self.name)" } required init(name: String) { // 必须实现的构造函数 self.name = name } convenience init(firstname:String,lastname: String) { //方便构造函数 self.init(name:firstname + "" + lastname) } func beAttacted(health:Int) -> Void { self.health -= health } // 加上final不能被子类重写 final func getHealth() -> Int { return self.health } } class Solider: Person { var weapon: String override var description: String { // 类的重载 return "i am a Solider,name:String) { // swift两段式构造,先构造子类的元素,再构造父类的元素 self.weapon = weapon super.init(name: name) } convenience init(weapon:String) { // 方便构造函数,调用自己已有的构造函数,无法调用super.init let name = "Solider" self.init(weapon: weapon,name:name) } convenience required init(name: String) { self.init(weapon: "gun",name:name) } } var s = Solider(firstname: "s",lastname: "r") s.weapon