Object-c 继承

父类MyRectangle.h

#import <Foundation/Foundation.h>


@interface MyRectangle : NSObject

{

    int width;

    int height;

}

-(MyRectangle*)initWithWidth:(int)w height:(int)h;

-(void)setWidth:(int)w;

-(void)setHeight:(int)h;

-(void)setWidth:(int)w height:(int)h;

-(int)width;

-(int)height;

-(void)print;

@end


MyRectangle.m

#import "MyRectangle.h"


@implementation MyRectangle

-(MyRectangle*)initWithWidth:(int)w height:(int)h{

    self=[super init];

    if(self){

        [self setWidth:w height:h];

    }

    return self;

}

-(void)setWidth:(int)w{

    width=w;

}

-(void)setHeight:(int)h{

    height=h;

}

-(void)setWidth:(int)w height:(int)h{

    width=w;

    height=h;

}

-(int)width{

    return width;

}

-(int)height{

    return height;

}

-(void)print{

    printf("width=%i  height=%i\n",width,height);

}

@end


子类Square.h

#import "MyRectangle.h"


@interface Square : MyRectangle

-(Square*)initWithSize:(int)s;

-(void)setSize:(int)s;

-(int)size;

@end


Square.m


#import "Square.h"


@implementation Square

-(Square*)initWithSize:(int)s{

    self=[super init];

    if(self){

        [self setSize:s];

    }

    return self;

}

-(void)setSize:(int)s{

    width=s;

    height=s;

}

-(int)size{

    return width;

}

//重写父类方法

-(void)setWidth:(int)w{

    printf("Square重写MyRectanglesetWidth方法\n");

    [self setSize:w];

}

-(void)setHeight:(int)h{

    printf("Square重写MyRectanglesetHeight方法\n");

    [self setSize:h];

}

@end



main.m

#import "MyRectangle.h"

#import "Square.h"

#import <stdio.h>


int main(int argc, const char * argv[])

{

    MyRectangle *rec=[[MyRectangle alloc]initWithWidth:10 height:20];

    Square *sq=[[Square alloc]initWithSize:15];

    

    printf("MyRectangle:");

    [rec print];

    

    printf("Square:\n");

    [sq print];

    

    //更新sq

    [sq setSize:18];

    printf("重写的Square\n");

    [sq print];

    

    //调用父类

    [sq setWidth:30];

    int d=[sq width];

    printf("调用父类且自己未重写的方法%i\n",d);

    

    //释放内存

    [rec release];

    [sq release];

}


运行结果


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值