首页 > 其他 > 详细

类的三大特性之一:多态[入门程序示例]

时间:2016-01-06 21:39:59      阅读:274      评论:0      收藏:0      [点我收藏+]

main:

 1 #import <Foundation/Foundation.h>
 2 #import "Animal.h"        
 3 #import "Fish.h"
 4 #import "Bird.h"
 5 
 6 void doAction(Animal *ani)
 7 {
 8     [ani action];       //用父类参数ani,调用父类中的action
 9 }
10 
11 int main(int argc, const char * argv[]) {
12     @autoreleasepool {
13         Animal *animal=[[Animal alloc]init];
14         Bird *bird=[[Bird alloc]init];
15         Fish *fish=[[Fish alloc]init];
16         
17         doAction(animal);           //传入父类实例animal
18         doAction(bird);             //传入子类实例bird
19         doAction(fish);             //传入子类实例fish
20     }
21     return 0;
22 }

Animal.h:

1 #import <Foundation/Foundation.h>
2 
3 @interface Animal : NSObject
4 -(void)action;
5 @end

Animal.m:

1 #import "Animal.h"
2 
3 @implementation Animal
4 -(void)action{
5     NSLog(@"Animal Moving~");
6 }
7 @end

Fish.h:

1 #import "Animal.h"
2 
3 @interface Fish : Animal
4 -(void)action;
5 @end

Fish.m:

1 #import "Fish.h"
2 
3 @implementation Fish
4 -(void)action{
5     NSLog(@"Fish Swiming~");
6 }
7 @end

Bird.h:

#import "Animal.h"

@interface Bird : Animal
-(void)action;
@end

Bird.m:

1 #import "Bird.h"
2 
3 @implementation Bird
4 -(void)action{
5     NSLog(@"Bird Flying~");
6 }
7 @end

类的三大特性之一:多态[入门程序示例]

原文:http://www.cnblogs.com/wangyang1987/p/5107376.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!