關(guān)于多態(tài)和OOP
多態(tài) (Polymorphism):
指計算機程序執(zhí)行時岔绸,相同的訊息可能會送給多個不同的類別之物件秦忿,而系統(tǒng)可依據(jù)物件所屬類別内颗,引發(fā)對應(yīng)類別的方法捻激,而有不同的行為制轰。簡單來說,所謂多型意指相同的訊息給予不同的物件會引發(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),并對同一源自類別動物(父類別)之一訊息有不同的響應(yīng)丈屹,如類別動物有「動()」之動作调俘,而類別老鷹會「飛()」伶棒,類別狗則會「跑()」,則稱之為多型彩库。
實踐:
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()