zoukankan      html  css  js  c++  java
  • Objective C多态

           面向对象的封装的三个基本特征是、继承和多态。

    包是一组简单的数据结构和定义相关的操作在上面的其合并成一个类,继承1种亲子关系,子类能够拥有父类定的成员变量、属性以及方法。

           多态就是指父类中定义的成员变量和方法被子类继承,父类对象能够表现出不同的行为。

    OC中的方法都是虚方法。执行时不看指针类型,依据生成对象的类型决定被调用的方法。

           以交通工具为例,定义父类为Vehicle,两个子类Bicycle、Car都继承自它,都拥有父类的成员变量name、属性height以及实例方法run

    “Vehicle.h”
    @interface Vehicle : NSObject
    {
        NSString *name;
    }
    @property(assign, nonatomic)int weight;
    -(void)run;
    @end
    <span style="font-family:SimHei;">"Bicycle.h"</span>
    @interface Bicycle : Vehicle
    @end
    "Car.h"
    @interface Car : Vehicle
    @end
           分别实现Car和Bicycle中的run方法

    @implementation Bicycle
    -(void)run
    {
        
        name=@"自行车";
        self.weight=100;
        NSLog(@"%@ %d", name , self.weight);
    }
    @end

    @implementation Car
    -(void)run
    {
        name=@"汽车";
        self.weight=2000;
        NSLog(@"%@ %d", name, self.weight);
    }
    @end

              在main.m中測试

    #import <Foundation/Foundation.h>
    #import "Vehicle.h"
    #import "Car.h"
    #import "Bicycle.h"
    int main(int argc, const char * argv[])
    {
    
        @autoreleasepool {
            Car *car=[[Car alloc]init];
            
            Bicycle *bike=[[Bicycle alloc]init];
            
            Vehicle *veh=car;
            [car run];
            veh = bike;
            [veh run];
        }
        return 0;
    }
    

    执行结果为:汽车 2000
                          自行车 100

    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    怎样编写YARN应用程序
    Oracle整形转字符串to_char()
    js 前加分号和感叹号的含义
    Android 多屏适配解决方式
    nginx负载均衡基于ip_hash的session粘帖
    mysql锁SELECT FOR UPDATE【转】
    redis主从复制
    mysql 优化实例之索引创建
    mysql sql优化实例
    MySQL 慢查询日志分析及可视化结果
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4619159.html
Copyright © 2011-2022 走看看