Objective-C个人学习系列(5) 面向对象(封装、继承、多态)
//get set 方法就是一个封装的案例
//不是将变量设置成public,而是将变量封装,通过get、set方法来访问
//类的继承------------------------------------------------
#import <Foundation/Foundation.h>
//定义父类
@interface Animal : NSObject{
int weight;
@privateint age;
@protectedint sex;
@public int type;
}
@property int age ,weight,sex,type;
-(id)init;
-(void)move;
@end
#import "Animal.h"
@implementation Animal
@synthesize age,sex,type,weight;
-(id)init{
self = [super init];
if (self!=nil) {
self.age = 25;
self.sex = 1;
self.type = 3;
self.weight = 50;
}
returnself;
}
-(void)move{
NSLog(@"Animal move !");
}
@end
#import "Animal.h"
//定义子类,继承父类Animal
@interface Dog : Animal{
int color;
int kind;
}
@property int color,kind;
-(id)init;
-(void)keepDoor;
-(void)move;
-(void)play;
@end
#import "Dog.h"
#import "Animal.h"
@implementation Dog
@synthesize color,kind;
-(id)init{
//self 指向自身(当前的实例对象)的指针对象,
//super 指向父类对象的指针
self = [superinit]; //子类重写init时必须先初始化父类
if (self) {
self.kind = 1;
self.color = 20;
}
returnself;
}
-(void)keepDoor{
color = 100;
kind = 2;
//继承父类的实例变量
type = 4;
sex = 1;
//age = 5; //父类中为private
weight = 60;
NSLog(@"I can Keep You Door!");
}
-(void)move{
NSLog(@"I can run speed!");
}
-(void)play{
}
@end
//--------多态---------------
/**
使用不同的类共享相同的方法名称的能力称为多态。
多态中的一组类,每个都能响应相同的一个方法名,每个类中定义的该方法都封装了不同都操作,
编译器在编译时不会去检查对象的类型,在运行时才会确定具体的类,并找到其方法调用,
如果子类没有该方法,则调用父类的方法。(参考动态类型、动态绑定)
<多态的三个前提条件:继承、重写、父类引用指向子类对象。>
**/
#import <Foundation/Foundation.h>
//定义父类
@interface Animal : NSObject
-(void)move;
@end
#import "Animal.h"
@implementation Animal
-(void)move{
NSLog(@"Animal Move 111");
}
@end
#import "Animal.h"
//定义子类,继承父类
@interface Dog : Animal
-(void)move;
@end
#import "Dog.h"
@implementation Dog
//重写父类方法
-(void)move{
NSLog(@"Dog move 222");
}
@end
#import <Foundation/Foundation.h>
#import "Animal.h"
#import "Dog.h"
#import "Cat.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Animal *a =[[Dog alloc]init]; //父类引用指向子类对象
[a move]; //Output:Dog move 222 此处调用的子类方法
//oc中id类型是个特殊的多态用法
NSMutableArray* arr = [[NSMutableArrayalloc]init];
//将不同的类用id类型存储到数组
for (int i = 0; i<5; i++) {
id pid = nil;
if (i%2==0) {
NSString* s = @"abc";
pid = s;
}else{
NSNumber *n = [NSNumber numberWithInt:i];
pid = n;
}
[arr addObject:pid];
}
for (int i = 0; i < 5; i++) {
id p = arr[i];
NSLog(@"%@",p); //该处调用父类的description方法
}
}
}