Objective-C Polymorphism

Objective-C图形类继承示例
本文通过Objective-C代码展示了如何使用类继承来实现不同形状的面积计算,包括正方形和矩形。提供了完整的源代码实现,从Shape基类派生出Square和Rectangle子类,并实现了各自的面积计算方法。
#import <Foundation/Foundation.h>

@interface Shape : NSObject 
{
  CGFloat area;
}
-(void)printArea;
-(void)calculateArea;
@end

@implementation Shape

-(void)printArea {
 NSLog(@"The area is %f",area);
}

-(void)calculateArea {
}

@end


@interface Square : Shape
{
  CGFloat length;
}

-(id)initWithSide : (CGFloat)side;
-(void)calculateArea;

@end


@implementation Square 

-(id)initWithSide : (CGFloat)side {
 length = side;
 return self;
}

-(void)calculateArea {
 area = length * length;
}

-(void)printArea {
 NSLog(@"The area of square is %f", area);
}

@end


@interface Rectangle : Shape 
{
 CGFloat length;
 CGFloat breadth;
}
-(id)initWithLength: (CGFloat)rLen andBreadth:(CGFloat)rBreadth;

@end


@implementation Rectangle

-(id)initWithLength: (CGFloat)rLen andBreadth:(CGFloat)rBreadth {
 length = rLen;
 breadth = rBreadth;
 return self;
}

-(void)calculateArea {
 area = length * breadth;
}

-(void)printArea {
 NSLog(@"The area of Rectangle is %f", area);
}

@end


int main(int ar, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
  Shape *square = [[Square alloc]initWithSide:4.2];
  [square calculateArea];
  [square printArea];
  Shape *rect = [[Rectangle alloc]initWithLength:7.88 andBreadth:6.35];
  [rect calculateArea];
  [rect printArea];
  
  [pool drain];
  return 0;
  
}

 

转载于:https://www.cnblogs.com/silva/p/5227815.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值