黑马程序员技术交流社区
标题:
类的三大特性,封装,继承,多态
[打印本页]
作者:
HiGodl
时间:
2015-9-21 23:36
标题:
类的三大特性,封装,继承,多态
本帖最后由 HiGodl 于 2015-9-21 23:37 编辑
类的三大特性,封装,继承,多态
封装:顾名思义,就是把类内部的东西保护起来,不让外界直接访问。也就是在其他地方不能直接访问类的成员变量,只能通过提供的函数间接的设置及获取(或者只能获取,或者只能设置,或者完全不能访问到)类的成员变量
OC的成员变量修饰符有@public、@protected、@private、@package,默认为@private
继承:就是子类的生成是依靠父类的,很多成员变量及方法属性之类都是从父类继承下来的,当然自己也可以有自己的特性,通过继承可以将一类事物的共有属性及实现方法统一放在一个父类中,具体事物再继承这个父类,这样可以减少代码冗余,增强程序的扩展性
多态:父类中方法根据形参中传入子类的不同而执行子类相应的方法,便于程序扩展。感觉这个能明白但说也说不太明白
直接看代码吧
#import <Foundation/Foundation.h>
/*首先定义Animal类作为父类,其成员变量_color,在程序外部是不能直接访问的,只能通过Animal提供的get和set方法设置或获取_color的值,这里就体现了类的封装特性*/
@interface Animal : NSObject{
NSString *_color;
}
//在@end之前为Animal类中方法的声明
//设置动物颜色
-(void) setColor:(NSString *)color;
//获取动物颜色
-(NSString *)_color;
//动物跑的方法
-(void)run;
//定义一个doRun的方法,通过传入动物得到动物跑的方法----后面会通过这个方法来体现多态的方便之处
-(void)doRun:(Animal *)animal;
@end //Animal
/*@implementation中为Animal中方法的具体实现,其中description,是继承自NSObject的,不需要在类中声明,该方法作用是定义打印对象实例时输出的内容*/
@implementation Animal
-(void) setColor:(NSString *)color{
_color = color;
}
-(NSString *)_color{
return _color;
}
-(NSString *)description{
return @" Animal";
}
-(void)run{
NSLog(@"Animal run");
}
-(void)doRun:(Animal *)animal{
[animal run];
}
@end //Animal
//接下来是Dog类,继承Animal类
@interface Dog : Animal
@end //Dog
/*
定义在Dog中Animal类的方法
在Dog中重新定义Animal中的方法(方法名,返回值,参数都相同),称为方法的重写
*/
@implementation Dog
-(void)run{
NSLog(@"Dog run");
}
-(NSString *)description{
return @" Dog";
}
@end //Dog
/*
定义在Cat中Animal类的方法
*/
@interface Cat : Animal
@end
@implementation Cat
-(void)run{
NSLog(@"Cat run");
}
-(NSString *)description{
return @" Cat";
}
@end
int main(int argc, const char * argv[]) {
/*
实例化Animal对象,也有另外一种实例化对象的方法,也就是通过new关键字:[Animal new]
但是[[Animal alloc] init]才是oc特有的,能体现出对象实例化的过程
先通过alloc分配内存,再通过init(类的构造方法)初始化对象
*/
Animal * ani = [[Animal alloc] init];
//实例化Dog对象
Dog *dog = [[Dog alloc] init];
//实例化Cat对象
Cat *cat = [[Cat alloc] init];
//设置ani颜色为黑色
[ani setColor:@"black"];
//设置dog颜色为金黄色
[dog setColor:@"golden"];
//设置cat颜色为灰色
[cat setColor:@"gray"];
//调用ani的run方法
[ani run];
//打印ani颜色并输出ani对象(也就是description方法中内容)
NSLog(@"%@ 色的%@",[ani _color],ani);
[cat run];
NSLog(@"%@ 色的%@",[cat _color],cat);
[dog run];
NSLog(@"%@ 色的%@",[dog _color],dog);
NSLog(@"=================多态的体现===================");
//Animal *ani2 = [[Cat alloc] init];
//Animal *ani3 = [[Dog alloc] init];
//[ani2 run];
//[ani3 run];
/*
通过多态程序中只需要实例化一个Animal对象即可
通过给Animal的doRun方法传递不同对象来调用不同对象自己的run方法
doRun方法中的[animal run],会自动判断传入对象的具体类型是什么,从而调用具体类型的run方法
这样极大的增强了程序的扩展性,当在有一个其他的Animal类时(如牛),只需要给doRun方法传入该对象实例即可调用该对象实例的run方法
*/
Animal *ani4 = [[Animal alloc] init];
[ani4 doRun:ani4]; //结果为---Animal run
[ani4 doRun:[[Cat alloc] init]]; //结果为---Cat run
[ani4 doRun:[[Dog alloc] init]]; //结果为---Dog run
return 0;
}
复制代码
以上是根据个人理解所写,有不准确或不正确的地方欢迎指正,大家一起进步呀~~~
作者:
黑白世界
时间:
2015-9-22 10:13
实现了多态才能实现面向对象。而实现多态需要依赖继承关系。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2