镔哥哥就不多说,简单介绍单面:
//
// Person.h
// 封装继承多态
//
// Created by apple on 14/12/29.
// Copyright (c) 2014年 huweibin. All rights reserved.
//
/*
封装:隐藏内部实现,稳定外部接口.
封装就是定义类定义属性 定义方法
*/
#import <Foundation/Foundation.h>
@interface Person : NSObject
//属性封装了setter get方法
@property(nonatomic,strong)NSString *name,*sex;
@property(nonatomic,assign)int age;
-(id)initWithName:(NSString *)name sex:(NSString *)sex age:(int)age;
-(Person *)work;
@end
Person.m
// 封装继承多态
//
// Created by apple on 14/12/29.
// Copyright (c) 2014年 huweibin. All rights reserved.
//
#import "Person.h"
@implementation Person
-(id)initWithName:(NSString *)name sex:(NSString *)sex age:(int)age
{
self = [superinit];
if (self) {
self.name = name;
self.sex = sex;
self.age = age;
}
return self;
}
-(Person *)work
{
NSLog(@"%@正在埋头工作",self.name);
return 0;
}
@end
// Worker.h
// 封装继承多态
//
// Created by apple on 14/12/29.
// Copyright (c) 2014年 huweibin. All rights reserved.
//
/*
继承:子类可以直接复用父类中的成员.子类继承父类所有方法的声明和实现非私有的实例变量以及协议 继承是要在.h中声明一下继承具有单根性和传递性
继承就是代码优化公共部分交给父类
*/
#import "Person.h"
@interface Worker : Person
@end
/
// Worker.m
// 封装继承多态
//
// Created by apple on 14/12/29.
// Copyright (c) 2014年 huweibin. All rights reserved.
//
#import "Worker.h"
@implementation Worker
@end
//
// King.h
// 封装继承多态
//
// Created by apple on 14/12/29.
// Copyright (c) 2014年 huweibin. All rights reserved.
//
#import "Person.h"
@interface King : Person
@end
//
// King.m
// 封装继承多态
//
// Created by apple on 14/12/29.
// Copyright (c) 2014年 huweibin. All rights reserved.
//
#import "King.h"
@implementation King
@end
//
// ViewController.h
// 封装继承多态
//
// Created by apple on 14/12/29.
// Copyright (c) 2014年 huweibin. All rights reserved.
/*
多态:不同对象对同一消息的不同响应.子类可以重写父类的方法
多态就是允许方法重名参数或返回值可以是父类型传入或返回
*/
#import <UIKit/UIKit.h>
#import "Worker.h"
#import "King.h"
@interface ViewController : UIViewController
@end
//
// ViewController.m
// 封装继承多态
//
// Created by apple on 14/12/29.
// Copyright (c) 2014年 huweibin. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
Worker *worker = [[Workeralloc]init];
worker.name = @"镔哥哥";
[worker work];//worker可以换为父类型Person
King *king = [[Kingalloc]init];
king.name = @"汉高祖";
[king work];//king可以换为父类型Person
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
原文地址:http://blog.csdn.net/sammyieveo/article/details/42235121