通过继承来扩展

main.m

#import <Foundation/Foundation.h>

#import "Rectangle.h"

int main(int argc, constchar * argv[]) {
 
    @autoreleasepool {
        Rectangle *myRect = [Rectanglenew];
        XYPoint *myPoint = [XYPointnew]; 
        myRect.width = 5;
        myRect.height = 8;
        //[myRect setWidth:5 andHeight:8];
        //[myPoint setX:10 andY:200];
 
        myPoint.x = 10;
        myPoint.y = 200;
 
        myRect.origin = myPoint;
        NSLog(@"Rectangle w = %i, h = %i",myRect.width,myRect.height);
        NSLog(@"Origin at (%i, %i)",myRect.origin.x,myRect.origin.y);
        NSLog(@"Area = %i, Perimeter = %i",[myRect area],[myRect perimeter]); 

    }

    return 0;

}

                                                                                                              

 
Rectangle.h
 
#import <Foundation/Foundation.h>
#import "XYPoint.h"
 
@interface Rectangle : NSObject               
//rectangle 矩形                                              
//origin    原点                                             
//perimeter 周长
 
@propertyint width, height;
//-(void)setWidth:(int) w andHeight: (int) h;

-(int)area;

-(int)perimeter;

//originsettergetter方法

-(XYPoint *) origin;

-(void) setOrigin: (XYPoint *) pt;

@end

 

 
Rectangle.m
 
#import "Rectangle.h"

@implementation Rectangle

{

    XYPoint *origin;                         // 原点

}

 

@synthesize width, height;

 

                                            //-(void)setWidth:(int) w andHeight: (int) h{

                                            //

                                            //    width = w;

                                            //    height = h;

                                            //}

-(int)area{

    

    returnwidth * height;

}

-(int)perimeter{

    

    return  (width + height) * 2;

}

 

                                            // 添加方法    originsteetr方法和getter方法

 

 

-(void) setOrigin: (XYPoint *) pt{

    

    origin = pt;

}

 

-(XYPoint *)origin{

    

    returnorigin;

}

 

 

@end

 

 
XYPoint.h
 
#import <Foundation/Foundation.h>

@interface XYPoint : NSObject

 

 

@propertyint x, y;

 

//-(void) setX:(int) xval andY: (int) yval;

 

 

@end

 

 
XYPoint.m
 
#import "XYPoint.h"

@implementation XYPoint

 

@synthesize x, y;

 

//-(void) setX:(int) xval andY: (int) yval{

//    

//    x = xval;

//    y = yval;

//}

@end

 

原文地址:https://www.cnblogs.com/GhostKZShadow/p/5105408.html