@fiy-fish
2015-07-18T11:28:54.000000Z
字数 1497
阅读 1555
Objective-c
// day06-03-继承//// Created by Aaron on 15/7/8.// Copyright (c) 2015年 Aaron. All rights reserved.//#import <Foundation/Foundation.h>//继承//继承是指从父类获得属性和方法//父类//父类是将所有的子类的公有特征综合起来//super class father class//子类,也被叫做派生类//子类除了会继承父类的特征,还可以派生出自己独有的特征//sub class child class#import "Student.h"int main(int argc, const char * argv[]) {@autoreleasepool {Student *std = [[Student alloc] initWithName:@"xiaobai" withAge:10];//子类继承父类 会将父类的方法继承过来NSString *name = [std name];//父类的属性 子类也会继承过来//NSLog(@"%@",name);[std eat];[Student test1];//父类里面不提供接口的方法,子类无法直接访问//[std setScore:100];//子类可以在父类的特征基础上添加自己的独有的属性//子类可以添加自己的方法//当父类的方法在子类里面不再适用的时候,需要重写}return 0;}//继承的作用: 当要创建大量的相似的类的时候,可以使用继承
#import "Person.h"@interface Student : Person{//在子类里面还可以产生自己独有的属性和方法NSInteger _score;}-(NSString *)name;-(void)setScore:(NSInteger)score;@end
#import "Student.h"@implementation Student-(NSString *)name{return _name;}-(void)setScore:(NSInteger)score{if(_score != score){_score = score;}NSLog(@"%ld",_score);}//重写父类方法的时候,不需要再提供接口-(void)eat{NSLog(@"用筷子挑食物");//在重写的时候,很多时候需要利用到父类的流程//仅仅是在原有的流程上添加一些操作[super eat];}@end
#import <Foundation/Foundation.h>@interface Person : NSObject{NSString *_name;NSInteger _age;}-(instancetype)initWithName:(NSString *)name withAge:(NSInteger)age;-(void)eat;+(void)test1;@end
#import "Person.h"@implementation Person-(instancetype)initWithName:(NSString *)name withAge:(NSInteger)age{if(self = [super init]){_name = name;_age = age;}return self;}-(void)eat{NSLog(@"张开嘴");NSLog(@"嚼");//[self test2];}-(void)test2{NSLog(@"test2");}+(void)test1{NSLog(@"test1");}@end
