------- ios培训android培训java培训、期待与您交流! ----------

黑马程序员 继承、组合、多态,NSString

-----------黑马程序员 IOS培训、Android培训、Java培训、期待与您交流----------------

#import <Foundation/Foundation.h>

@interface Person : NSObject

{

    int _age;

    int _height;

}

- (void)run;

@end

@implementation Person

- (void)run

{

    NSLog(@"person甩起来跑!");

}

@end

@interface Score : NSObject

    int _cScore;

    int _ocScore;

@end

@implementation Score

 

@end

// Student类继承Person类:可以拥有Person类里的所有方法和成员变量

@interface Student : Person

   //这是组合,Student类拥有Score类:可以拥有Score类里的所有方法和成员变量

   Score *score;

    int _no;

}

- (void)run;

- (void)playBasketball;

@end

@implementation Student

- (void)run

{

     NSLog(@"student甩起来跑!");

}

- (void)playBasketball

{

     NSLog(@"学生在打篮球!");

}

@end

void exam(Person *p)

{

       NSLog(@"p在考试!");

}

int main()

{

    //这是多态,父类指针指向子类对象,通过动态绑定可知stu实际形象指向Student对象,有继承才有多态

   Person *stu = [Student new];

   // 从结果输出的是"student甩起来跑"可以知道stu是指向Student对象

   [stu run];

   // 调用playBasketball方法编译器会先从Person类中寻找,如果没有寻找到编译器就会发出警告说没有这个方法,实际上stu是指向Student对象,运行时会动态绑定调用Student类的对象方法

   [stu playBasketball];

   // 用父类指针做形参,子类和父类都可以传递

    exam(stu);

    // @"123456"是一个对象,这是一个创建字符串的方法

    NSString *str = @"123456";

    // 更多的是用这个创建字符串

    [NSString stringWithFormat:@"............"]

  return 0;

}

 

posted on 2014-05-07 21:06  wtb  阅读(165)  评论(0编辑  收藏  举报

导航

------- ios培训android培训java培训、期待与您交流! ----------