定义父类
- 我们在父类的.h文件中申明了3个属性sex age name 和三个方法
//
// 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
- 然后我们在 .m文件中实现这三个方法
//
// 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
- 分别创建dog 和cat 子类
-
dog 类
.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
-
cat类
.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;
}
日志分析

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