实现Square类,让其继承自Rectangle类,并在Square类增添新属性和方法

本文详细介绍了使用Objective-C设计矩形和正方形类的过程。通过继承机制,正方形类从矩形类中派生,实现了面积和周长的计算方法。文章展示了如何设置边长并重写计算方法以适应正方形的特性。

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

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface Rectangle : NSObject{
 4     int width;
 5     int height;
 6 }
 7 @property int width,height;
 8 -(int) area;
 9 -(int) perimeter;
10 -(void)setWidth:(int)w andHeight:(int)h;
11 
12 @end
13 
14 
15 #import "Rectangle.h"
16 
17 @implementation Rectangle
18 @synthesize width,height;
19 -(void)setWidth:(int)w andHeight:(int) h{
20     width=w;
21     height=h;
22 }
23 -(int) area{
24     return width*height;
25 }
26 -(int) perimeter{
27     return (width+height)*2;
28 }
29 
30 @end
31 
32 
33 
34 #import <Foundation/Foundation.h>
35 #import "Rectangle.h"
36 @interface Square : Rectangle
37 -(void) setSide:(int) s;
38 -(int)side;
39 -(int)area;
40 -(int)perimeter;
41 
42 @end
43 
44 
45 #import "Square.h"
46 
47 @implementation Square
48 
49 -(void) setSide:(int) s{
50     [self setWidth:s andHeight:s];
51 }
52 
53 -(int) side{
54     return width;
55 }
56 
57 -(int)area{
58     return width*width;
59 }
60 
61 -(int)perimeter{
62     return 2*(width+height);
63 }
64 @end

 

转载于:https://www.cnblogs.com/wsq724439564/p/3272914.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值