1、继承的基本概念
程序的世界和人类的“对象”世界在思想上是没有什么区别的,富二代继承了父母,自然就拥有了父母拥有的所有资源,子类继承了父类同样就拥有了父类所有的方法和属性(成员变量)。
- 继承的好处:
(1)抽取出了重复的代码
(2)建立了类和类之间的联系 - 重写(继承的另一部分)
子类可以从父类继承方法,但是有时候父类的方法不适合子类,子类就可以写一个自己的同名方法,覆盖掉父类的同名方法,叫做重写。
重写的时候,在子类的.h中不必重新声明,直接在.m中写实现就可以。
3、多态的基本概念
- 多态在代码中的体现,即为多种形态,必须要有继承,没有继承就没有多态。
- 在使用多态是,会进行动态检测,以调用真实的对象方法
- 多态在代码中的体现即父类指针指向子类对象。
直接看一个很简单的例子吧
图形为父类,三角形和圆形为子类
父类
//声明部分
@interface Shape : NSObject
/**
* 点,图形由点构成
*/
@property(nonatomic,assign ) NSPoint P1;
/**
* 图得有颜色吧
*/
@property(nonatomic,strong) NSString* color;
/**
* 画图形的方法
*/
-(void)draw;
@end
//实现部分
#import "Shape.h"
@implementation Shape
-(void)draw{
}
@end
子类三角形
//声明部分
#import "Shape.h"
@interface Triangle : Shape
//添加的自己的属性宽
@property(nonatomic,assign) int width;
//高
@property(nonatomic,assign) int height;
//添加了自己的构造方法
-(Triangle * ) initWithPoint_1:(NSPoint) point_1 Width:(int) aWidth Height :(int ) aHeight;
+(Triangle * ) triangleWithPoint_1:(NSPoint) point_1 Width:(int) aWidth Height :(int ) aHeight;
@end
//实现部分
#import "Triangle.h"
@implementation Triangle
//重写父类继承来的方法
-(void)draw{
NSLog(@"draw a triangle at (%g,%g) in %@ ,its weight is %d and height is %d",self.P1.x,self.P1.y,self.color,self.width,self.height);
}
//构造器方法部分不做细说,第2天已说过
@end
子类圆
//声明部分
#import "Shape.h"
@interface circle : Shape
//半径
@property(nonatomic,assign) double r;
//初始化部分
-(id) initWithPoint :(NSPoint) apoint r:(int) aR;
+(id) circleWithPoint :(NSPoint) apoint r:(int) aR;
@end
实现部分
#import "circle.h"
@implementation circle
//重写父类方法
-(void)draw{
[super draw];
NSLog(@"drwa at a point (%g,%g) with r =%g in %@",self.P1.x,self.P1.y,self.r,self.color);
}
//构造器方法部分不做细说,第2天已说过
@end
在main.m 中体现多态
#import <Foundation/Foundation.h>
#import "circle.h"
#import "Triangle.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSPoint p={1,3};
//父类指针指向子类对象,分别指向圆和三角形(这边也
//指里氏替换)
//调用一样的draw方法,不过结果不一样,
//即多态的体现
Shape *c=[circle circleWithPoint:p r:2];
[c draw];
Shape *t=[Triangle triangleWithPoint_1:p Width:2 Height:3];
[t draw];
}
return 0;
}
结果
2015-08-12 13:44:57.638 shape[1093:86640] drwa at a point (1,3) with r =2 in (null)
2015-08-12 13:44:57.640 shape[1093:86640] draw a triangle at (1,3) in (null) ,its weight is 2 and height is 3