zoukankan      html  css  js  c++  java
  • 多态

    继承

    1.在Oc中每个类对象最开始的位置都会有一个isa指针,该指针指向一块内存区域,分发表中先找本类,再找父类方法.

     2. self在实例方法中表示指向当前对象指针,在类方法中需要[self class]。用“_下划线”访问没调用get set方法,加self.后实际上调用了其成员的get set方法。


    1.多态:建立在继承之上,同一类型对象对同一方法呈现不同的实现(方法)状态。(即“一个接口多个方法”的意思,属于经常用到的情况)

    2.多态的实现方法:

    • 虚函数(接口):运行时多态。用处当父类定义的方法不易实现的时候。虚函数即只声明不实现的抽象基类。现实场景:领导下达命令让手下做。发生在上层。
    • 重写:运行时多态。用处当子类继承父类的方法时,父类不能满足子类的需求。发生在子类与父类之间(中下层),金字塔模型。
    • 重载:操作性(编译时运行)多态。不建立在继承基础之上,目前oc不支持重载。

    3.通过定义一个通用的调用方法,以简化调用(好处符合单一责任原则):

    如:在虚函数中定义-(void)show;-(void)showContext;

      实现-(void)show{},-(void)showContext{[self show]};

    4.id动态数据类型

    • id是指向任何一个继承NSObject对象的指针,设置nil。
    • 当需要定义一个不知道什么类型的时候使用,在编码阶段不报任何警告。
    • 可以对其发送任何存在的(消息)方法

    Animal.h

    @interface Animal : NSObject
    {
        NSString *_name;
    }
    @property(nonatomic,retain)NSString *name;
    
    -(Animal *)initWithName:(NSString *)aName;
    
    /*
    声明虚函数(方法)
    */
    -(void)learn;
    
    /*
    统计学习的内容
    */
    -(void)statisInfo;
    @end

    Animal.m

    #import "Animal.h"
    
    @implementation Animal
    @synthesize name = _name;
    
    -(Animal *)initWithName:(NSString *)aName
    {
        self = [super init];
        if (self)
        {
            self.name = aName;
        }
        return self;
    }
    /*
    虚函数:什么都不用实现
     */
    -(void)learn
    {
        
    }
    
    //统计学习内容
    -(void)statisInfo
    {
       //NSLog(@"第%d个",++i);
        [self learn];
    }
    @end

    Preson.h

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

    Preson.m

    #import "Person.h"
    @implementation Person
    
    -(void)learn
    {
       
        NSLog(@"学习吃东西");
    }
    @end

    Student.h

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

    Student.m

    #import "Student.h"
    
    
    @implementation Student
    -(void)learn
    {
        [super learn];
        NSLog(@"学习ios开发技能");
    }
    
    @end

    AppDelegate.m

    #import "AppDelegate.h"
    #import "Animal.h"
    #import "Person.h"
    #import "Student.h"
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        // Override point for customization after application launch.
        self.window.backgroundColor = [UIColor whiteColor];
        
        Animal *s = [[Student alloc]initWithName:@"jobs"];
        [s statisInfo];
    
        [self.window makeKeyAndVisible];
        return YES;
    }
  • 相关阅读:
    【nodejs】使用Node.js实现REST Client调用REST API
    [Groovy] Groovy && JNI
    一些很实用的Maven Plugins
    秋天到了
    今天头好疼
    想起那个人的时候
    不知道标题
    生活让我懂得
    显示实现接口和实现接口
    Foreach原理
  • 原文地址:https://www.cnblogs.com/huen/p/3517914.html
Copyright © 2011-2022 走看看