搜索
您的当前位置:首页正文

OC:多态☀️

来源:二三娱乐
  • 版权声明:本文为博主原创文章,未经博主允许不得转载。

1、多态 父类指针指向子类对象

 没有继承就没有多态.

封装:隐藏内部实现,稳定外部接口.
     封装就是定义类 定义属性 定义方法

属性:封装了setter get方法

Person.h
@property(nonatomic,retain)NSString *name,*sex;
类封装了实例变量和方法

@interface Person : NSObject
{
    NSString *_name;
    NSString *_sex;
    int _age;
}

@property(nonatomic,retain)NSString *name,*sex;
@property(nonatomic,assign)int age;
- (id)initWithName:(NSString *)name sex:(NSString *)sex age:(int)age;
-(Person *)work;
@end


Person.m
#import "Person.h"
@implementation Person
@synthesize name = _name,sex = _sex,age = _age;
- (id)initWithName:(NSString *)name sex:(NSString *)sex age:(int)age
{
    self = [super init];
    if (self) {
        self.name = name;
        self.sex = sex;
        self.age = age;
    }
    return self;
}
- (Person *)work
{
    NSLog(@"%@正在工作",self.name);
    return 0;
}
@end

2、继承

子类可以直接复用父类中的成员.子类继承父类所有方法的声明和实现 非私有的实例变量以及协议 继承是要在.h中声明一下 继承具有单根性和传递性.
继承就是代码优化公共部分交给父类.

#import "Person.h"
@interface Worker : Person
@end

#import "Person.h"
@interface King : Person
@end```

###3、多态
  
>不同对象对同一消息的不同响应.子类可以重写父类的方法
多态就是允许方法重名 参数或返回值可以是父类型传入或返回

import "AppDelegate.h"

import "Worker.h"

import "Actor.h"

import "King.h"

Top