關于多態(tài)和OOP
多態(tài) (Polymorphism):
指計算機程序執(zhí)行時,相同的訊息可能會送給多個不同的類別之物件,而系統(tǒng)可依據(jù)物件所屬類別,引發(fā)對應類別的方法,而有不同的行為。簡單來說,所謂多型意指相同的訊息給予不同的物件會引發(fā)不同的動作稱之。
Polymorphism allows the expression of some sort of contract, with potentially many types implementing that contract (whether through class inheritance or not) in different ways, each according to their own purpose. Codeusingthat contract should not have to care about which implementation is involved, only that the contract will be obeyed.
例子:
比如有動物(Animal)之[類別](Class),而且由動物[繼承]出類別老鷹(Hawk)和類別狗(Dog),并對同一源自類別動物(父類別)之一訊息有不同的響應,如類別動物有「動()」之動作,而類別老鷹會「飛()」,類別狗則會「跑()」,則稱之為多型。
實踐:
import UIKit
class Animal {
func move() {
}
}
class Dog: Animal {
override func move() {
print("Run")
}
}
class Hawk: Animal {
override func move() {
print("Fly")
}
}
let dog = Dog()
let hawk = Hawk()
dog.move()
hawk.move()