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

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

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

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

4.多態的侷限性
不能訪問子類的屬性(能夠考慮強制轉換)指針

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

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 }
相關文章
相關標籤/搜索