objective C中继承、协议、分类和多态的实现

本文介绍了Objective-C中四种核心特性:继承、协议、分类和多态的实现方式。通过代码示例展示了如何使用继承创建类层次结构,利用协议实现类似接口的功能,使用分类为已有类添加新方法,以及多态在运行时的动态绑定。通过这些特性,Objective-C可以灵活地构建和扩展软件系统。
摘要由CSDN通过智能技术生成
第一、objective C中继承的实现
在oc中只有实例变量会有权限控制,实例方法和类方法是没有权限控制的,这点与c++不同,OC默认的是protected,并且在声明权限控制时,没有分号
在OC中可以像C++一样用指针运算法来访问实例变量
Rectangle.h 文件代码:
#import <Foundation/Foundation.h>


@interface Rectangle : NSObject
{
    int _width;
    int _height;
}
@property (nonatomic,assign) int width;
@property (nonatomic,assign) int height;
-(Rectangle *) initWithWidth:(int)w AndHeight:(int)h;
-(void) print;
@end
Rectangle.m 文件代码:


#import "Rectangle.h"


@implementation Rectangle
@synthesize width=_width;
@synthesize height=_height;
-(Rectangle *) initWithWidth:(int)w AndHeight:(int)h
{
    self=[super init];
    if(self)
    {
    self.width=w;
    self.height=h;
    }
    return self;
}
-(void)print
{
    NSLog(@"the height is %d ,the width is %d",self.height,self.width);
}
@end


Square.h 文件代码:
#import "Rectangle.h"


@interface Square : Rectangle
{
    int _d;

-(Square *)initSquareWithwidth:(int)w AndHeight:(int)h Andval:(int)d;
@property (nonatomic,assign)int d;
@end


Square.m 文件代码:
#import "Square.h"


@implementation Square
@synthesize d=_d;
-(Square*)initSquareWithwidth:(int)w AndHeight:(int)h Andval:(int)d
{
    self=[super init];
    if(self)
    {
    self.height=h;
    self.width=w;
    self.d=d;
    }
    return self;
}
-(void)print //实现重载
{
    NSLog(@"the d is %d,the width is %d,the height is %d",self.d,self.width,self.height);
}
@
main函数:


#import <Foundation/Foundation.h>
#import "Access.h"
#import "Re
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值