标签:
继承的其中一个很重要的目的是为了实现多态。我们现在先来看看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 : NSObject 12 @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 Peason 12 @synthesize name=_name; 13 @synthesize age=_age; 14 -(id)initWithName:(NSString*)name Age:(int)age 15 { 16 Peason* p=[[Peason alloc]init]; 17 p.name=name; 18 p.age=age; 19 return p; 20 } 21 -(void)Say 22 { 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 : Peason 12 -(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 Student 12 -(void)Say 13 { 14 NSLog(@"My name is %@. I am student.",self.name); 15 } 16 -(id)initWithName:(NSString*)name Age:(int)age 17 { 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.
注意:如果子类想用和父类一样的初始化方法那么需要重新写一遍,如果不重写直接使用父类的初始化方法,那么得到的是一个父类的对象
标签:
原文地址:http://www.cnblogs.com/zhangjingyangjinjin/p/4622232.html