定義兩個類別, 用到繼承, 類別裡包含屬性和方法。 然後用類別生出物件 存取物件的屬性和呼叫物件的方法。

目的:類別繼承的簡單應用。

Photo by Roman Kraft on Unsplash

說明:

於 Playground 內先 import UIKit.

import UIKit

建立第一個類別(Dog)

class Dog{
var dogName = "Lucky"
func toCatch(_ text:String){
print("Dog \(dogName) to catch the \(text).")
}
}

建立第二個類別(Cat)

重點:類別 Cat 繼承了 Dog 的所有特性。

class Cat:Dog{
var catName = "Mimi"
func toRun(_ text:String){
print("Cat \(catName) to run \(text).")
}
}

利用 Cat 類別生出 animal 物件

let animal = Cat()

接下來就可以來看看以下 print 出來的結果了:

animal.toCatch("ball")

可以呼叫 Class Dog 的 toCatch function.

Print : Dog Lucky to catch the ball.

animal.dogName = "Cola"animal.toCatch(“bone”)

也可更改類別 Dod 內的變數 dogName 為 Cola,並呼叫 toCatch function.

Print : Dog Cola to catch the bone.

animal.toRun(“fast”)

當然也可呼叫本身類別 Cat 的 toRun function.

Print : Cat Mimi to run fast.

animal.catName = “Judy”animal.toRun(“slow”)

當然也可更改類別 Cat 內的變數 catName 為 Judy

Print : Cat Judy to run slow.

完整程式:

import UIKit// 類別 Dog
class Dog{
var dogName = "Lucky"
func toCatch(_ text:String){
print("Dog \(dogName) to catch the \(text).")
}
}
// 類別 Cat 繼承了 Dog 的所有特性
class Cat:Dog{
var catName = "Mimi"
func toRun(_ text:String){
print("Cat \(catName) to run \(text).")
}
}
// 利用 Cat 類別生出 animal 物件
let animal = Cat()
animal.toCatch("ball")
animal.dogName = "Cola"
animal.toCatch("bone")
animal.toRun("fast")
animal.catName = "Judy"
animal.toRun("slow")

--

--