OC语言——多态

一,多态概念:

   对象会具有多种形态。多态的条件是继承。

  Person *p = [Student new];

  p->age = 90;

  [p walk];

  子类对象赋值给父类指针

  父类指针访问对应的属性和方法

  父类不能调用子类特有的方法,但可以强转换。

二,用代码来说明一下

#import <Foundation/Foundation.h> //必须包含这个框架,这里面有很多类。
//------Animal------
@interface  Animal : NSObject
- (void)eat;
@end

@implementation Animal
- (void)eat
{
    NSLog(@"Animal吃东西!!!");
}
@end
//------Dog------
@interface Dog : Animal
@end

@implementation Dog
- (void)eat          //重写了父类的eat行为
{
    NSLog(@"Dog吃东西!!!");
}
@end
//-----Cat-------

@interface Cat : Animal
@end

@implementation Cat
 - (void)eat          //重写了父类的eat行为
 {
 NSLog(@"cat eat eat ");
 }
@end
//-----main-------
int main()
{
    Animal *c = [Cat new]; // 可以父类指向子类,但注意这里猫不能继承狗
    Dog *d = [Dog new];
    
    //多态:狗是一个狗类,另外也是一个种动物类型,SO称为多态
    //父类指针指向子类对象。
    Animal *a = [Dog new];
    
    [a eat];
    //会调用真实类型的方法Dog,而不是调用Animal
    
    //NSObject *e = [Animal new];
    //NSObject *f = [Dog new];
    
    NSString *s = [Cat new];
    //NSString是系统自带的类
    
    return 0;
}

三,多态的好处

//-----------------------------多态好处1-----------------------------
#import <Foundation/Foundation.h>

@interface  Animal : NSObject
- (void)eat;
@end

@implementation Animal
- (void)eat
{
    NSLog(@"Animal吃东西!!!");
}
@end
//-----Dog-------
@interface Dog : Animal
@end

@implementation Dog
- (void)eat
{
    NSLog(@"Dog吃东西!!!");
}
@end
//-------Cat-----
@interface Cat : Animal
@end

@implementation Cat
- (void)eat
{
    NSLog(@"cat eat eat ");
}
@end
//------------
//  void feed(Dog *d)
//  {
//      [d eat];
//  }
//  void feed2(Cat *c)
//  {
//      [c eat];
//  }
//------------
void feed(Animal *c)
//用上面的整合为一句,如果参数写的是父类,子类也可以传进来。
{
    [c eat];
}
int main()
{
    Animal *dd = [Animal new];
    feed(dd);
    //调用函数后,会把对象指针dd传给函数形参,多态的好处
    
    Cat *cc = [Cat new];
    feed(cc);
 
    return 0;
}

//-----------------------------多态好处2-----------------------------
#import <Foundation/Foundation.h>

@interface  Animal : NSObject
- (void)eat;
@end

@implementation Animal
- (void)eat
{
    NSLog(@"Animal吃东西!!!");
}
@end
//------Dog------
@interface Dog : Animal
- (void)run;
@end

@implementation Dog
- (void)eat
{
    NSLog(@"Dog吃东西!!!");
}
- (void)run
{
    NSLog(@"多态的局限性");
}
@end
//-----Cat-------
@interface Cat : Animal
@end

@implementation Cat
- (void)eat
{
    NSLog(@"cat eat eat ");
}
@end

void feed(Animal *c)
{
    [c eat];
}

int main()
{
    Animal *aa = [Animal new];
    //[aa run];
    //父类类型的指针变量不能调用子类的方法。
    
    Dog *dd = (Dog *)aa;
    [dd run];
    //可以强类型转换
    
   //  Animal *dd = [Animal new];
   // feed(dd);
    
   // Cat *cc = [Cat new];
   // feed(cc);
   return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值