iOS 繼承&類方法

躍然發表於2016-07-19

閒言少敘,直接上程式碼:

#import <Foundation/Foundation.h>
@interface Circle : NSObject
@property (nonatomic,assign) float diameter;
-(instancetype) initWithDiameter:(float)d;
@end
#import "Circle.h"
@implementation Circle
-(instancetype) init {
    return [self initWithDiameter:3];
}
-(instancetype) initWithDiameter:(float)d {
    self = [super init];
    if (self) {
        self.diameter = d;
    }
    return self;
}
@end
#import "Circle.h"
@interface ColoredCircle : Circle
@property (nonatomic,retain) NSString* color;
-(instancetype) initWithDiameter:(float)d andColor:(NSString*)c;
+(ColoredCircle*) star;
@end
#import "ColoredCircle.h"
@implementation ColoredCircle
-(instancetype) init {
    return [self initWithDiameter:6 andColor:@"blue"]; // default diameter is 6, default color is "blue"
}
-(instancetype) initWithDiameter:(float)d andColor:(NSString *)c {
    self = [super initWithDiameter:d];
    if (self) {
        self.color = c;
    }
    return self; 
}
+(ColoredCircle*) star {
    ColoredCircle *s = [[ColoredCircle alloc] initWithDiameter:1.0 andColor:@"white"];
    return s;
}
@end

相關文章