class Cat { private var name : String private var shoutNum = 3 init(name: String) { self.name = name } init() { self.name = "No name" } func Shout() -> String{ var res = "" for i in 0 ..< shoutNum { res = res + "Meow " } return"My name is \(self.name), \(res)" } var ShoutNum: Int { get { return self.shoutNum } set { if newValue <= 10 { shoutNum = newValue }else{ shoutNum = 10 } } } } let cat = Cat(name:"MiMi") cat.shoutNum = 5 print(cat.Shout())
class Animal { var name : String init(name: String) { self.name = name } init() { self.name = "No name" } var shoutNum = 3 var ShoutNum: Int { get { return self.shoutNum } set { shoutNum = newValue } } func Shout() -> String{ var res = "" for _ in 0 ..< shoutNum { res = res + "Meow " } return"My name is \(self.name), \(res)" } }
class Cat : Animal { override init() { super.init() } override init(name: String) { super.init(name:name) } override func Shout() -> String{ var res = "" for _ in 0 ..< shoutNum { res = res + "Meow " } return"My name is \(self.name), \(res)" } }
class Dog : Animal { override init() { super.init() } override init(name: String) { super.init(name:name) } override func Shout() -> String{ var res = "" for _ in 0 ..< shoutNum { res = res + "Wang " } return"My name is \(self.name), \(res)" } }
繼承缺點:父類別變動 -> 子類別也會跟著變,破壞封裝,增加父類子類之間的耦合
繼承時機: 兩者之間是 is-a 關係可以,has-a 關係不行
多型
假設目前需要儲存動物陣列,並依序發出叫聲
多型表示:不同物件但是可以執行相同的動作,但會透過他們各自實現的程式碼來執行
1 2 3 4 5 6 7 8 9 10
var array:[Animal] = [] array.append(Cat(name:"小花")) array.append(Dog(name:"小黃")) array.append(Dog(name:"小黑")) array.append(Cat(name:"小毛")) array.append(Cat(name:"咪咪"))
for idx in 0..<array.count { print("array[\(idx)] = \(array[idx].Shout())") }
class Animal { var name : String init(name: String) { self.name = name } init() { self.name = "No name" } var shoutNum = 3 var ShoutNum: Int { get { return self.shoutNum } set { shoutNum = newValue } } func Shout() -> String{ var res = "" for _ in 0 ..< shoutNum { res = res + getShoutSound() } return"My name is \(self.name), \(res)" } func getShoutSound() -> String{ return"" } }