您的位置:首页 > 编程语言 > C语言/C++

OC语言学习 (六) 继承、多态,构造方法,description方法

2014-12-10 18:20 549 查看
声明父类Animal继承自NSObject

Animal.h

#ifndef oc_Animal_h
#define oc_Animal_h
@interface Animal : NSObject {
@public
int weight;
}
- (void)eat;

//重写默认构造方法
- (id) init;
//自定义构造方法
- (id) initWithWeight:(int)newWeight;

@end

#endif


Animal.m
#import <Foundation/Foundation.h>
#import "Animal.h"

@implementation Animal

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

//id 是万能指针,可指向任何对象, 不要再加上*
//重写默认构造方法init  构造方法:初始化对象
- (id) init
{
if (self = [super init]) { //!=nil   先初始化父对象,再赋给self, 再初始化自有成员, 最后return self
weight = 20;
}
return self;
}

//自定义构造方法
- (id) initWithWeight:(int)newWeight
{
if (self = [super init]) {
self->weight = newWeight;
}
return self;
}
@end


子类Dog,继承自Animal
Dog.h

#ifndef oc_Dog_h
#define oc_Dog_h
#import "Animal.h"
@interface Dog : Animal {
@public
int speed;
}

@property int speed; //自动声明 get set方法

- (void)run;

//id 是万能指针,可指向任何对象, 不要再加上*
//重写init  构造方法:初始化对象
- (id) init; //重写 NSObject的init

- (id) initWithWeightSpeed:(int)newWeight:(int)newSpeed;

- (NSString*)description; //对象描述   //重写 NSObject的description
+ (NSString*)description; //类对象描述

@end

#endif


Dog.m

#import <Foundation/Foundation.h>
#import "Dog.h"

@implementation Dog

@synthesize speed; //编译器自动生成get、set的实现方法

- (void)run {
NSLog(@"跑-速度:%d", speed);
}

//id 是万能指针,可指向任何对象, 不要再加上*
//重写init  构造方法:初始化对象
- (id) init
{
if (self = [super init]) { //!=nil
speed = 15;
//self->speed = 15;
}
return self;
}

//自定义构造方法,调用父类自定义构造
- (id) initWithWeightSpeed:(int)newWeight:(int)newSpeed
{
if (self = [super initWithWeight:newWeight]) {
speed = newSpeed;
}
return self;
}
- (NSString*)description //对象描述   //重写 NSObject的description
{
return [NSString stringWithFormat:@"weight=%d,speed=%d", weight, speed];
}
+ (NSString*)description //类对象描述
{
return [NSString stringWithUTF8String:"<Dog : Animal>"];
}

@end


main.m

#import "Animal.h"
#import "Dog.h"
int main()
{
Animal* animal = [[Animal alloc] init]; //默认构造
[animal eat];
animal = [[Animal alloc] initWithWeight:17]; //自定义构造
[animal eat];

Dog* adog = [[Dog alloc] init];//默认构造
[adog run];
[adog eat];
adog = [[Dog alloc] initWithWeight:16];//父类的自定义构造
[adog eat];
adog = [[Dog alloc] initWithWeightSpeed:16:13];//Dog自身的 自定义构造
[adog run];
[adog eat];

//多态创建对象
Animal* xdog = [[Dog alloc] initWithWeightSpeed:33 :55];
[xdog eat];
Dog* mdog = xdog;
[mdog run];

//description方法调用
NSLog([mdog description]); //调用对象方法
NSLog(@"%@", mdog);//输出对象%@  默认调用description对象方法
NSLog([Dog description]); //调用类方法
NSLog([[Dog class] description]); //默认调用 description类方法  这里省略了@"%@"的format

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐