objective-c : 构造类、继承及实例

来源:互联网 发布:java中static什么意思 编辑:程序博客网 时间:2024/06/05 17:46

今天,我们来实现如下UML,并作为objective-c的第二个例子,介绍如何自己构造类,实现继承,并如何实例化,赋值等:

 

            +--------------------------+
            |       Phone              |
            |--------------------------|
            | LCDSize                |
            | Color                      |
            +-------------------------+
            | SetLCDSize          |
            | SetColor               |
            | Performance        |
            +--------------------------+
               ^                           ^
               |                            |
               |                            |
   +-----------+-------------+       +-+--------------+
   |      miPhone            |       | mPearPhone     |
   |-------------------------|         |----------------|
   |                         |              |                |
   |                         |              |                |
   +-------------------------+       |                |
   +                         |             |                |
   |                         |             +----------------+
   |                         |             +                |
   |   Performance        |       |  Performance   |
   +-------------------------+       |                |
                                           +----------------+

 

代码实现如下:

#import <Foundation/Foundation.h>

typedef enum {
  RED,
  WHITE,
  BLACK
}PHONECOLOR;

NSString *getColorStr(PHONECOLOR c)
{
    switch(c)
    {
        case RED: return @"red";
        case WHITE: return @"white";
        case BLACK: return @"black";
        default: return @"no color";
    }
}

@interface Phone: NSObject
{
    float LCDSize;
    PHONECOLOR color;
}

-(void) SetLCDSize : (float)size;
-(void) SetColor : (PHONECOLOR)c;
@end

@implementation Phone
-(void) SetLCDSize : (float)size
{
    LCDSize = size;
}

-(void) SetColor : (PHONECOLOR)c
{
    color = c;
}

//empty
-(void) Performance
{
}
@end

//-----iPhone "is a" Phone. it has all feature what a phone posess
@interface iPhone: Phone
@end

@implementation iPhone
-(void) Performance
{
     NSLog(@"iPhone performance: LCD-%1.1f Color-%@", LCDSize, getColorStr(color));
}
@end

//----PearPhone "is a" Phone too.
@interface PearPhone: Phone
@end

@implementation PearPhone
-(void) Performance
{
    NSLog(@"Pear Phone performance: LCD-%1.1f Color-%@", LCDSize, getColorStr(color));
}
@end


int main(int argc, const char *argv[])
{
    PHONECOLOR mcolor = WHITE;
    id iphone;
    iphone = [iPhone new];
    [iphone SetLCDSize: 4.0];
    [iphone SetColor: mcolor];

    [iphone Performance];

    id pearphone;
    pearphone = [PearPhone new];
    [pearphone SetLCDSize: 4.5];
    mcolor = BLACK;
    [pearphone SetColor: mcolor];

    [pearphone Performance];       

 return (0);
}

 

 

 

原创粉丝点击