class Penson: NSObject {
var name = ""
var age = 0
var height = 0.0
var weight = 0.0
func dosomething(){
print("做事情")
}
}
let per = Person()
per.name = "人民群众"
per.dosomething() //人民群众做事情
class Student: Person {
var hobby = ""
func play() {
print("玩耍")
}
}
let stu = Student()
stu.name = "小明"
stu.hobby = "游泳"
stu.dosomething() //小明做事情
使用override
关键字为覆盖定义添加前缀
class Student: Person {
var hobby = ""
override func dosomething() {
print("\(name)喜欢\(hobby)")
}
}
let stu = Student()
stu.name = "小明"
stu.hobby = "游泳"
stu.dosomething() //小明喜欢游泳
使用final
关键字来阻止它被覆盖
class Person: NSObject {
var name = ""
var age = 0
var height = 0.0
var weight = 0.0
final func dosomething(){
print("\(name)做事情")
}
}
这样子类将无法重写dosomething方法,编译器提示错误为Instance method overrides a 'final' instance method