swift類、繼承、介面,swift類繼承介面

來源:互聯網
上載者:User

swift類、繼承、介面,swift類繼承介面

import Foundationclass Hello{        var _name:String?="swift global"        init(name:String){                    //定義類中有參數的構造方法        _name=name;        println("Hello , \(name)");    }        init(){                                //定義類中無參數的構造方法        println("this is init method");    }        func sayHello(){                       //定義成員方法        println("hello \(_name)")    }        class func meClass(){                 //定義類方法        println("this is class method");    }    }class Hi:Hello{    override func sayHello() {          //繼承Hello類,並重載 其成員方法        super.sayHello()                //調用父類的方法        println("hloo override \(_name)");    }}class HiChild:Hi{}                      //繼承Hi類extension Hi{                           //動態擴充 Hi 類,增加一個成員方法, 繼承了Hi 類的子類也可以調用這個方法    func sayHaha(){        println("HHHaaa");    }}var h1 = Hello()                        //執行個體Hello類,調用無參的init方法 ,輸出this is init method
var h2 = Hello(name:"Hello init")     //調用有參的init方法,輸出:Hello , Hello init
var hi = Hi()       //執行個體化子類,會調用父類的無參構造方法,輸出this is init method
hi.sayHello() //調用類的方法,輸出hello Optional("swift global") 和 hloo override Optional("swift global")

var h3 = HiChild() //執行個體化,調用父類的父類的構造方法,輸出this is init method

h3.sayHaha() //父類擴充了一個方法,則其子類可以調用這個方法,輸出 HHHaaa
h3.sayHello() //調用父類的方法,輸出hello Optional("swift global") 和 hloo override Optional("swift global")

Hello.meClass() //調用類方法,輸出this is class method

 

 

介面

protocol People{           //protocal 定義一個介面    func getName()->String  //介面中申明一個方法,該方法返回一個字串 }class Man:People {          //實現該介面    func getName() -> String {   //實現介面的類 必須實現介面中所有的方法        return "zhangsan"    }}var m = Man()println("Name is \(m.getName())")

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.