OC——繼承

來源:互聯網
上載者:User

標籤:

繼承的其中一個很重要的目的是為了實現多態。我們現在先來看看OC的繼承。

一、繼承

父類:

標頭檔

 1 // 2 //  Peason.h 3 //  01-繼承和多態 4 // 5 //  Created by zhangjing on 15/7/5. 6 //  Copyright (c) 2015年 zhangjing. All rights reserved. 7 // 8  9 #import <Foundation/Foundation.h>10 11 @interface Peason : NSObject12 @property NSString *name;13 @property int age;14 15 -(id)initWithName:(NSString*)name Age:(int)age;16 -(void)Say;17 @end

實現檔案:

 1 // 2 //  Peason.m 3 //  01-繼承和多態 4 // 5 //  Created by zhangjing on 15/7/5. 6 //  Copyright (c) 2015年 zhangjing. All rights reserved. 7 // 8  9 #import "Peason.h"10 11 @implementation Peason12 @synthesize name=_name;13 @synthesize age=_age;14 -(id)initWithName:(NSString*)name Age:(int)age15 {16     Peason* p=[[Peason alloc]init];17     p.name=name;18     p.age=age;19     return p;20 }21 -(void)Say22 {23     NSLog(@"%@_____%@",self,self.name);24 }25 @end

子類:

標頭檔

 1 // 2 //  Student.h 3 //  01-繼承和多態 4 // 5 //  Created by zhangjing on 15/7/5. 6 //  Copyright (c) 2015年 zhangjing. All rights reserved. 7 // 8  9 #import "Peason.h"10 11 @interface Student : Peason12 -(id)initWithName:(NSString*)name Age:(int)age;13 -(void)Say;14 @end

實現檔案

 1 // 2 //  Student.m 3 //  01-繼承和多態 4 // 5 //  Created by zhangjing on 15/7/5. 6 //  Copyright (c) 2015年 zhangjing. All rights reserved. 7 // 8  9 #import "Student.h"10 11 @implementation Student12 -(void)Say13 {14     NSLog(@"My name is %@. I am student.",self.name);15 }16 -(id)initWithName:(NSString*)name Age:(int)age17 {18     Student* s=[[Student alloc]init];19     s.name=name;20     s.age=age;21     return s;22 }23 @end

調用函數

 1 // 2 //  main.m 3 //  01-繼承和多態 4 // 5 //  Created by zhangjing on 15/7/5. 6 //  Copyright (c) 2015年 zhangjing. All rights reserved. 7 // 8  9 #import <Foundation/Foundation.h>10 #import "Peason.h"11 #import "Student.h"12 13 int main(int argc, const char * argv[]) {14     @autoreleasepool {15         Peason* p=[[Peason alloc]initWithName:@"Tom" Age:14];16         [p Say];17         Student* s=[[Student alloc]initWithName:@"Jack" Age:12];18         [s Say];19     }20     return 0;21 }

輸出結果:

2015-07-05 15:32:51.221 01-繼承和多態[1281:44755] <Peason: 0x100206a30>_____Tom

2015-07-05 15:32:51.222 01-繼承和多態[1281:44755] My name is Jack. I am student.

注意:如果子類想用和父類一樣的初始化方法那麼需要重新寫一遍,如果不重寫直接使用父類的初始化方法,那麼得到的是一個父類的對象

OC——繼承

聯繫我們

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