oc 基础继承

2021-03-23  本文已影响0人  xq9527

定义父类

//
//  Animal.h
//  inherit
//
//  Created by xuqing on 2021/3/22.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Animal : NSObject{
    @public
    NSString * _sex;
    NSUInteger _age;
    NSString* _name;
}
@property(nonatomic, copy)NSString * name;
- (instancetype)initWithsex:(NSString * )sex age:(NSUInteger)age;
-(void)eat;
-(void)bark;
@end
NS_ASSUME_NONNULL_END
//
//  Animal.m
//  inherit
//
//  Created by xuqing on 2021/3/22.
//
#import "Animal.h"
@implementation Animal
- (instancetype)initWithsex:(NSString * )sex age:(NSUInteger)age{
    self=[super init];
    if(self){
        _sex=sex;
        _age=age;
    }
    return  self;
}
-(void)eat{
 
}
-(void)bark{

}
@end

.h 文件申明

//
//  Dog.h
//  inherit
//
//  Created by xuqing on 2021/3/22.
//

#import "Animal.h"

NS_ASSUME_NONNULL_BEGIN

@interface Dog : Animal

@end

NS_ASSUME_NONNULL_END

.m文件实现

//
//  Dog.m
//  inherit
//
//  Created by xuqing on 2021/3/22.
//

#import "Dog.h"
@implementation Dog
- (void)eat{
    NSLog(@"eat bone");
}

@end

.h文件申明

 //
//  Cat.h
//  inherit
//
//  Created by xuqing on 2021/3/22.
//
#import "Animal.h"
NS_ASSUME_NONNULL_BEGIN
@interface Cat : Animal
@end
NS_ASSUME_NONNULL_END

.m文件实现

 //
//  Cat.m
//  inherit
//
//  Created by xuqing on 2021/3/22.
//
#import "Cat.h"
@implementation Cat
- (void)eat{
    NSLog(@"eat food");
   
}
- (NSString *)description{
    return [NSString stringWithFormat:@"sex =%@ , age=%zd", _sex,_age];
}
@end

具体实例化调用

//
//  main.m
//  inherit
//
//  Created by xuqing on 2021/3/18.
//

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

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        
        Animal *animal=[[Animal alloc]initWithsex:@"male" age:1];
        [animal eat];
        
        Dog * dog =[[Dog alloc]initWithsex:@"Female" age:5];
        dog.name=@"tom";
    
        [dog eat];
    
        animal= [[Cat alloc]initWithsex:@"Male" age:10];
        animal.name=@"Kitty";
        [animal eat];

        NSLog(@"%@",animal);

    }
    return 0;
   
}

日志分析


通过观察日志 我们看到 子类实现了父类的对象指针也是可以的 然后调用子类重写父类的方法 也是可以的
此文记录学习用
上一篇 下一篇

猜你喜欢

热点阅读