【學習筆記】【OC語言】多態,學習筆記oc多態

來源:互聯網
上載者:User

【學習筆記】【OC語言】多態,學習筆記oc多態

1.多態的基本概念
某一類事物的多種形態
OC對象具有多態性

2.多態的體現
Person *p = [Student new];
p->age = 100;
[p walk];
子類對象賦值給父類指標
父類指標訪問對應的屬性和方法

3.多態的好處
用父類接收參數,節省代碼

4.多態的局限性
不能訪問子類的屬性(可以考慮強制轉換)

5.多態的細節
動態綁定:在運行時根據對象的類型確定動態調用的方法

6.代碼

  1 #import <Foundation/Foundation.h>  2   3 /*  4  多態  5  1.沒有繼承就沒有多態  6  2.代碼的體現:父類類型的指標指向子類對象  7  3.好處:如果函數\方法參數中使用的是父類類型,可以傳入父類、子類對象  8  4.局限性:  9  1> 父類類型的變數 不能 直接調用子類特有的方法。必須強轉為子類類型變數後,才能直接調用子類特有的方法 10  */ 11  12 // 動物 13 @interface Animal : NSObject 14 - (void)eat; 15 @end 16  17 @implementation Animal 18 - (void)eat 19 { 20     NSLog(@"Animal-吃東西----"); 21 } 22 @end 23  24 // 狗 25 @interface Dog : Animal 26 - (void)run; 27 @end 28  29 @implementation  Dog 30 - (void)run 31 { 32     NSLog(@"Dog---跑起來"); 33 } 34 - (void)eat 35 { 36     NSLog(@"Dog-吃東西----"); 37 } 38 @end 39  40 // 貓 41 @interface Cat : Animal 42  43 @end 44  45 @implementation Cat 46 - (void)eat 47 { 48     NSLog(@"Cat-吃東西----"); 49 } 50 @end 51  52 // 這個函數是專門用來喂動畫 53 //void feed(Dog *d) 54 //{ 55 //    [d eat]; 56 //} 57 // 58 //void feed2(Cat *c) 59 //{ 60 //    [c eat]; 61 //} 62 // 63  64 // 如果參數中使用的是父類類型,可以傳入父類、子類對象 65 void feed(Animal *a) 66 { 67     [a eat]; 68 } 69  70 int main() 71 { 72     // NSString *d = [Cat new]; 73     // [d eat]; 74      75     /* 76     Animal *aa = [Dog new]; 77     // 多態的局限性:父類類型的變數 不能 用來調用子類的方法 78     //[aa run]; 79      80     // 將aa轉為Dog *類型的變數 81     Dog *dd = (Dog *)aa; 82      83     [dd run]; 84     */ 85      86     //Dog *d = [Dog new]; 87      88     //[d run]; 89      90     /* 91     Animal *aa = [Animal new]; 92     feed(aa); 93      94     Dog *dd = [Dog new]; 95     feed(dd); 96      97     Cat *cc = [Cat new]; 98     feed(cc); 99      */100     101     /*102     // NSString *s = [Cat new];103     Animal *c = [Cat new];104     105     106     NSObject *n = [Dog new];107     NSObject *n2 = [Animal new];108     109     110     // 多種形態111     //Dog *d = [Dog new]; // Dog類型112     113     // 多態:父類指標指向子類對象114     Animal *a = [Dog new];115     116     // 調用方法時會檢測對象的真實形象117     [a eat];118     */119     return 0;120 }

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.