Superclass & Subclass
subclass子類別可以繼承Superclass父類別的方法與屬性。
若要生成兩個相似的物件,可以先寫A類別(父類別)的程式碼生成一個物件,再寫B類別作為A的子類別,B類別除了會繼承A類別的方法與屬性,也能加入B類別自己特有的方法與屬性。
入虎穴
//Superclass
class Baby{
var name:String
var age:Int
func sleep(){
print("sleep")
}
func introduceSelf(){
print("My name is \(name)")
}
init(){
name = "Tom"
age = 1
}
init(name:String){
self.name = name
self.age = 1
}
init(age:Int){
self.age = age
self.name = "Sophie"
}
init(name:String, age:Int){
self.name = name
self.age = age
}
}
得虎子
//Subclass
class CuteBaby:Baby{
//設置子類別自己的屬性及方法
var nickname = "QQ"
func danceAndSing(){
print("dance and sing")
}
}
let iAmSoQ:CuteBaby = CuteBaby()
iAmSoQ.name //Tom
iAmSoQ.sleep() //sleep
iAmSoQ.danceAndSing() //dance and sing
iAmSoQ.nickname //QQ
老子都不老子了
Override覆寫:子類別呼叫繼承的方法時,做出跟父類別不一樣的行為。
//Override
override func sleep() {
print("sleep with cute smile")
super.sleep()
override func introduceSelf() {
print("My name is \(nickname)")
}
}
iAmSoQ.sleep()
//sleep with cute smile
//sleep
iAmSoQ.introduceSelf()
//My name is QQ
如何覆寫init方法?
override init(){
nickname = "QQ"
super.init()
name = "Sunny"
}