继承和封装
声明Rectangle类继承NSObject父类
#import <Foundation/Foundation.h>
@interface Rectangle : NSObject
@property int width , height ;
- (void)setWidth:(int)w andHeight :(int) h ;
- (void)caculate ;
//声明类方法
+ (void)textPrint ;
@end
实现Rectangle类
#import "Rectangle.h"
@implementation Rectangle
@synthesize width ,height ;
//在声明部分声明一个caculate方法,封装三种方法。
//这三种方法可以不用在声明部分声明 直接在实现部分实现 通过调用self自己的指针 实现三种方法
- (void)caculate{
[self area];
[self perimeter];
[self print] ;
}
-(void) setWidth:(int)w andHeight :(int)h {
width = w ;
height = h ;
}
-(int) area {
return width * height ;
}
-(int) perimeter {
return ( width + height ) * 2 ;
}
-(void) print {
NSLog(@"area = %i , perimeter = %i ",[self area] , [self perimeter]) ;
}
//实现类方法
+ (void) textPrint {
Rectangle *rec = [[Rectangle alloc]init];
[rec setWidth:2 andHeight:4];
[rec caculate] ;
}
@end
Square类的声明 继承Rectangle类
#import "Rectangle.h"
@interface Square : Rectangle
//声明side的setter方法和getter方法
-(void)setSide : (int) s ;
-(int)side ;
@end
Square类的实现
#import "Square.h"
@implementation Square
-(void)setSide:(int)s {
//通过self可以调用父类方法
[self setWidth:s];
[self setHeight:s] ;
}
-(int)side {
return [self width] ;
}
@end
main函数部分
#import <Foundation/Foundation.h>
#import "Rectangle.h"
#import "Square.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Rectangle *myRect = [[Rectangle alloc] init] ;
Square *squ = [[Square alloc]init] ;
[myRect setWidth:3 andHeight:4] ;
[myRect caculate];
//调用类方法 通过类名调用
[Rectangle textPrint] ;
[squ setSide:2] ;
[squ caculate] ;
}
return 0;
}
代码运行结果
/*这行结果是执行了
[myRect setWidth:3 andHeight:4] ;
[myRect caculate]; 的结果 赋值完 到caculate方法 调用了自己三种方法
*/
area = 12 , perimeter = 14
//通过调用类方法实现的
area = 8 , perimeter = 12
//Square类 通过继承Rectangle类 调用父类的方法实现
area = 4 , perimeter = 8