OC-5-三大特性:继承

----------  CornerFly真诚期待与您交流! ----------

 
一、继承的基本用法


1、设计两个类Bird、Dog

// Bird的声明
@interface Bird : NSObject
{
	@public
	int weight;
}
- (void)eat;
@end
// Bird的定义
@implementation Bird
- (void)eat {
	NSLog(@"吃吃吃-体重:%d", weight);
}
@end
// Dog的声明
@interface Dog : NSObject
{
	@public
	int weight;
}
- (void)eat;
@end
// Dog的定义
@implementation Dog
- (void)eat {
	NSLog(@"吃吃吃-体重:%d", weight);
}
@end


2、这两个类有相同的属性,可以抽取一个父类Animal。

 

// Animal的声明

@interface Animal : NSObject
{
	@public
	int weight;
}

- (void)eat;

@end

// Animal的定义

@implementation Animal
- (void)eat
{
	NSLog(@"吃吃吃-体重:%d", weight);
}
@end

 

3、子类可以在父类的基础上拓充属性和方法

 

// Bird的声明

@interface Bird : Animal

{

	@public
	int height;

}

- (void)fly;

@end

// Bird的定义

@implementation Bird

- (void)fly

{

	NSLog(@"飞飞飞-高度:%d", height);

}

@end

// Dog的声明

@interface Dog : Animal

{

	@publicint speed;

}

- (void)run;

@end

// Dog的定义

@implementation Dog

- (void)run

{

	NSLog(@"跑跑跑-高度:%d", speed);

}

@end

 

二、继承的使用场合

 

1、当两个类拥有相同属性和方法的时候,就可以将相同的东西抽取到一个父类中去

2、当A类完全拥有B类中的部分属性和方法时,可以考虑让B类继承A类

 

三、继承的好处和坏处

 

1、可以在不改变原来模型的基础上,拓充方法

2、建立了类与类之间的联系

3、抽取了公共代码

4、坏处:耦合性强

 

四、使用注意

 

1、子类方法和属性的访问过程:如果子类没有,就去访问父类的

2、不允许父类和子类拥有相同名称的成员变量

3、子类重新实现父类中的某个方法(重写),会覆盖父类以前的做法。

4、NSObject是全部OC类的最终父类。

5、OC中的继承是单继承,也就是一个类不可以继承两个或者两个以上的类。

 

五、继承和组合

1、当A类是B类时,可以让A类继承B类。

2、当A类拥有B类时,使用组合。

 

六、super

 

1、作用

1>直接调用父类中的某个方法。

2>super处在对象方法中,那么就调用父类的对象方法。

 super处在类方法中,就会调用父类的类方法。

2、使用场合:子类重写父类的方法时想保留父类的方法时。

3、代码示例

#import <Foundation/Foundation.h>

// 僵尸
@interface Zoombie : NSObject
- (void)walk;
+ (void)test;
- (void)test;
@end

@implemmentation Zoombie
+ (void)test
{
	NSLog(@"Zoombie+test");
}

- (void)test
{
	NSLog(@"Zoombie-test");
}

- (void)walk
{
	NSLog(@"往前挪两步******");
}
@end

// 跳跃僵尸
@interface JumpZoombie : Zoombie
+ (void)haha;
- (void)haha2;
@end

@implementation JumpZoombie
+ (void)haha
{
	[super test];
}
- (void)haha2
{
	[super test];
}
- (void)walk
{
	// 跳两下
	NSLog(@"跳两下");

	// 走两下(直接调用父类的walk方法)
	[super walk];
	NSLog(@"网前挪两步------");
}
@end

int main()
{
	//[JumpZoombie test];
	JumpZoombie *jz = [JumpZoombie new];
	//[jz walk];
	[jz haha2];
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值