继承的其中一个很重要的目的是为了实现多态。我们现在先来看看OC的继承。
一、继承
父类:
头文件
//
// Peason.h
// 01-继承和多态
//
// Created by zhangjing on 15/7/5.
// Copyright (c) 2015年 zhangjing. All rights reserved.
// #import <Foundation/Foundation.h> @interface Peason : NSObject
@property NSString *name;
@property int age; -(id)initWithName:(NSString*)name Age:(int)age;
-(void)Say;
@end
实现文件:
//
// Peason.m
// 01-继承和多态
//
// Created by zhangjing on 15/7/5.
// Copyright (c) 2015年 zhangjing. All rights reserved.
// #import "Peason.h" @implementation Peason
@synthesize name=_name;
@synthesize age=_age;
-(id)initWithName:(NSString*)name Age:(int)age
{
Peason* p=[[Peason alloc]init];
p.name=name;
p.age=age;
return p;
}
-(void)Say
{
NSLog(@"%@_____%@",self,self.name);
}
@end
子类:
头文件
//
// Student.h
// 01-继承和多态
//
// Created by zhangjing on 15/7/5.
// Copyright (c) 2015年 zhangjing. All rights reserved.
// #import "Peason.h" @interface Student : Peason
-(id)initWithName:(NSString*)name Age:(int)age;
-(void)Say;
@end
实现文件
//
// Student.m
// 01-继承和多态
//
// Created by zhangjing on 15/7/5.
// Copyright (c) 2015年 zhangjing. All rights reserved.
// #import "Student.h" @implementation Student
-(void)Say
{
NSLog(@"My name is %@. I am student.",self.name);
}
-(id)initWithName:(NSString*)name Age:(int)age
{
Student* s=[[Student alloc]init];
s.name=name;
s.age=age;
return s;
}
@end
调用函数
//
// main.m
// 01-继承和多态
//
// Created by zhangjing on 15/7/5.
// Copyright (c) 2015年 zhangjing. All rights reserved.
// #import <Foundation/Foundation.h>
#import "Peason.h"
#import "Student.h" int main(int argc, const char * argv[]) {
@autoreleasepool {
Peason* p=[[Peason alloc]initWithName:@"Tom" Age:];
[p Say];
Student* s=[[Student alloc]initWithName:@"Jack" Age:];
[s Say];
}
return ;
}
输出结果:
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.
注意:如果子类想用和父类一样的初始化方法那么需要重新写一遍,如果不重写直接使用父类的初始化方法,那么得到的是一个父类的对象