我的OC练习(三)- 类的继承实践练习

来源:互联网 发布:牛轧糖 知乎 编辑:程序博客网 时间:2024/05/16 08:56

为了练习类的继承,熟悉@public@private和@protected的使用,我做了下面一个练习。

练习工程为五个文件:main.m, Animal.h, Animal.m, Dog.h, Dog.m


内容如下:

main.m:

////  main.m//  2nd////  Created by Morning on 2015/11/08.//  Copyright © 2015年 Morning. All rights reserved.//#import <Foundation/Foundation.h>#import "Dog.h"int main(int argc, const char * argv[]) {    @autoreleasepool {        // insert code here...        Dog* dog = [Dog new];//创建狗类        [dog setAge:12];//调用dog的set对象方法,对从animal继承过来的实例常量赋值        [dog setName:@"Wang!"];        [dog setTypeId:1];        NSLog(@"姓名:%@年龄:%d,种类:%d",[dog name],[dog age],[dog typeId]);//输出结果    }    return 0;}


Animal.m:

////  Animal.m//  1st////  Created by Morning on 2015/11/08.//  Copyright © 2015年 Morning. All rights reserved.//#import "Animal.h"@implementation Animal-(void)setAge:(int)age{//由于是_age是private的实例变量,所以通过Animal自身提供的set方法可以对age进行赋值,便于子类使用    _age=age;}-(int)age{//同理要设置一个_age的get方法    return _age;}@end

Animal.h:

////  Animal.h//  1st////  Created by Morning on 2015/11/08.//  Copyright © 2015年 Morning. All rights reserved.//#import <Foundation/Foundation.h>@interface Animal : NSObject{    @public//公开的    NSString* _name;    @protected//保护的    int _typeId;    @private//私有的    int _age;}-(void)setAge:(int)age;-(int)age;@end


Dog.h:

////  Dog.h//  1st////  Created by Morning on 2015/11/08.//  Copyright © 2015年 Morning. All rights reserved.//#import <Foundation/Foundation.h>#import "Animal.h"@interface Dog : Animal//继承于Animal,所以继承了所有Animal的实例常量。//实例常量的set方法-(void)setName:(NSString*)name;-(void)setAge:(int)age;-(void)setTypeId:(int)typeId;//实例常量的get方法-(NSString*)name;-(int)age;-(int)typeId;@end



Dog.m:

////  Dog.m//  1st////  Created by Morning on 2015/11/08.//  Copyright © 2015年 Morning. All rights reserved.//#import "Dog.h"@implementation Dog-(void)setName:(NSString*)name{    _name=name;}-(void)setAge:(int)age{    [super setAge:age];//由于基类中_age是私有的,所以要通过调用父类提供的set方法才能对其进行赋值,所以此处顺便复习了super关键字}-(void)setTypeId:(int)typeId{    _typeId=typeId;}-(NSString*)name{    return _name;}-(int)age{    return [super age];//同set一样,私有变量的get方法也需要通过调用父类的get方法。}-(int)typeId{    return _typeId;}@end






0 0