Objective-C中的封裝、繼承、多態、分類,objective-c多態

來源:互聯網
上載者:User

Objective-C中的封裝、繼承、多態、分類,objective-c多態

封裝的好處:

繼承的好處:

繼承的注意點:

繼承和組合:

 1 @interface Score : NSObject 2 { 3         int _cScore; 4         int _ocScore;   5 } 6 @end 7  8 @implementation Score 9 @end10 11 @interface Student : NSObject12 {13        Score *_socre;  // 這裡用到組合,因為不能說成績是個學生14        int _age;  15 }16 @end17 18 @implementation Student19 @end

組合和繼承可以這樣理解:

  • 繼承是 xxx 是 xxx
  • 組合是 xxx 擁有 xxx

多態:不同的對象已自己的方式響應相同名稱方法的能力稱為多態

多態簡單的說就是:父類指標指向子類對象

多態的好處:

  • 用父類接收參數,節省代碼
#import <Foundation/Foundation.h>@interface Animal : NSObject@end@implementation Animal- (void)eat{    NSLog(@"Animal----eat food");}@end@interface Dog : Animal@end@implementation Dog- (void)eat{    NSLog(@"Dog----eat food");}@end@interface Cat : Animal@end@implementation Cat- (void)eat{    NSLog(@"Cat----eat food");}@end// 參數中使用的父類類型,可以傳入子類、父類對象void feed(Animal *a){        [a eat];}// 這個函數體現了多態的好處,節省了代碼int main(){        Animal *aa = [[Animal alloc] init];        feed(aa);        Dog *dd = [[Dog alloc] init];        feed(dd);        Cat *cc = [[Cat alloc] init];        feed(cc);}

多態的局限性:

  • 父類類型的變數 不能 直接調用子類的特有方法 (要用到強制轉換)
// 強制轉換Person *p = [[Student alloc] init];// 假如學習是學生特有的方法,如果想調用需要強制轉換// OC是弱文法如果用[p study]也可以(是動態綁定),但由於編譯器會出現警告,所以不要這麼寫用強制轉換 讓其更合理Student *s = (Student *)p;[s study];
  • 動態綁定:在運行時根據對象的類型確定動態調用的方法

分類-Category:

分類的作用:在不改變原來類內容的基礎上,可以為類增加一些方法 (便於合作開發)

分類的使用注意:

相關文章

聯繫我們

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