美文网首页
Swift 学习日记 Day1

Swift 学习日记 Day1

作者: 点点就是我 | 来源:发表于2017-08-12 17:01 被阅读5次

    关于多态和OOP

    多态 (Polymorphism):

    指计算机程序执行时,相同的讯息可能会送给多个不同的类别之物件,而系统可依据物件所属类别,引发对应类别的方法,而有不同的行为。简单来说,所谓多型意指相同的讯息给予不同的物件会引发不同的动作称之。

    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()
    

    相关文章

      网友评论

          本文标题:Swift 学习日记 Day1

          本文链接:https://www.haomeiwen.com/subject/qwxjrxtx.html