继承

作者:追风剑情 发布于:2019-2-21 20:41 分类:Objective-C

示例一

main.m

#import <Foundation/Foundation.h>

// ClassA 的声明
@interface ClassA : NSObject
{
    int x;
}
-(void) initVar;
@end

@implementation ClassA
-(void) initVar
{
    x = 100;
}
@end

// ClassB 的声明和定义
@interface ClassB : ClassA
-(void) printVar;
@end

@implementation ClassB
-(void) printVar
{
    NSLog(@"x = %i", x);
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        ClassB *b = [[ClassB alloc] init];
        
        [b initVar];
        [b printVar];
    }
    return 0;
}

运行测试
222.png

示例二:通过继承来扩展(添加新方法)

Rectangle.h

//
//  Rectangle.h
//  ObjectivCTest
//
//  Created by XXX on 2019/2/21.
//  Copyright © 2019 XXX. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Rectangle : NSObject

@property int width, height;

-(int) area;
-(int) perimeter;
-(void) setWidth: (int) w andHeight: (int) h;

@end


Rectangle.m

#import "Rectangle.h"

@implementation Rectangle

@synthesize width, height;

-(void) setWidth: (int) w andHeight: (int) h
{
    width = w;
    height = h;
}

// 求在积
-(int) area
{
    return width * height;
}

// 求周长
-(int) perimeter
{
    return (width + height) * 2;
}

@end


main.m

#import <Foundation/Foundation.h>
#import "Rectangle.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Rectangle *myRect = [[Rectangle alloc] init];
        
        [myRect setWidth: 5 andHeight: 8];
        
        NSLog(@"Rectangle: w = %i, h = %i", myRect.width, myRect.height);
        NSLog(@"Area = %i, Perimeter = %i", [myRect area], [myRect perimeter]);
    }
    return 0;
}

运行测试
333.png


示例三:在示例二的基础上新增Square类

Square.h

#import "Rectangle.h"

@interface Square : Rectangle

-(void) setSide: (int) s;
-(int) side;

@end


Square.m

#import "Square.h"

@implementation Square: Rectangle

// 设置边长
-(void) setSide: (int) s
{
    [self setWidth: s andHeight: s];
}

-(int) side
{
    return self.width;
}

@end


main.m

#import <Foundation/Foundation.h>
#import "Square.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Square *mySquare = [[Square alloc] init];
        
        [mySquare setSide: 5];
        
        NSLog(@"Square: s = %i", [mySquare side]);
        NSLog(@"Area = %i, Perimeter = %i", [mySquare area], [mySquare perimeter]);
    }
    return 0;
}

运行测试
444.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号