LHF Objective-C语法(6)继承

本文介绍了一个使用Objective-C实现的矩形和正方形类。通过继承关系,正方形类从矩形类中继承了基本属性,并添加了自己的特性。文中展示了如何创建这些形状对象并计算它们的面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyRectangle.h

//========================================== #import <Foundation/Foundation.h> @interface MyRectangel:NSObject{ int width; int height; } -(MyRectangel*) initWithWidth:(int) weight andHeight:(int) height; -(void) setWidth:(int) width; -(void) setHeight:(int) height; -(int)width; -(int)height; -(void) area; @end //=============================================== #import "MyRectangle.h" -(MyRectangel*) initWithWidth:(int) weight andHeight:(int) height{ self = [supert init]; if(self){ [self setWidth:w]; [self setHeight:h]; } } -(void) setWidth:(int) w{ width = w; } -(void) setHeight:(int) h{ height = h; } -(int)width{ return width; } -(int)height{ return height; } -(void) area{ NSLog(@"%d",width*height); } @end
正方形

//正方形继承矩形=============================================== #import "MyRectangle.h" @interface MySquare:MyRectangle{ int size; } -(MySquare*) initWithSize:(int)size; -(void) setSize:(int) size; -(int)size; @end //=============================================== #import "MySquare.h" @implementation MySquare -(MySquare*) initWithSize:(int)s{ self = [super init]; if(self){ [self setWidth:s]; [self setHeight:s]; } //return self; } -(void) setSize:(int) s{ size = s; } -(int)size{ return size; } @endmain.m

//=============================================== @import "MySquare.h" int main(argc,const char * argv[]){ MyRectangel *r = [[MyRectangle alloc] initWithWidth:2 andHeight:5]; [r area]; MySquare *s = [[MySquare alloc] initWithSize:6]; [s area];//调用父类的方法,计算面积 [r release]; [s release]; }


转载于:https://www.cnblogs.com/landebug/archive/2012/02/14/2416672.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值