Objective-C - 组合

本文通过实例演示了在Objective-C中如何实现面向对象编程,包括类的定义、初始化方法、属性设置以及对象间的关联。具体展示了Tire、Engine和Car三个类的创建过程,以及它们之间的继承和组合关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#import <Foundation/Foundation.h>


// --------------------------------------------------

@interface Tire : NSObject
@end // Tire


@implementation Tire

- (NSString *) description
{
    return (@"I am a tire. I last a while");
} // description

@end // Tire



// --------------------------------------------------

@interface Engine : NSObject
@end // Engine


@implementation Engine

- (NSString *) description
{
    return (@"I am an engine.  Vrooom!");
} // description

@end // Engine


// --------------------------------------------------

@interface Car : NSObject
{
    Engine *engine;
    Tire *tires[4];
}

- (void) print;

@end // Car


@implementation Car

- (id) init
{
    if (self = [super init]) {
        engine = [Engine new];
        
        tires[0] = [Tire new];
        tires[1] = [Tire new];
        tires[2] = [Tire new];
        tires[3] = [Tire new];
    }
    
    return (self);
    
} // init

- (void) print
{
    NSLog (@"%@", engine);
    
    NSLog (@"%@", tires[0]);
    NSLog (@"%@", tires[1]);
    NSLog (@"%@", tires[2]);
    NSLog (@"%@", tires[3]);
    
} // print

@end // Car


// --------------------------------------------------

int main (int argc, const char * argv[]) 
{
    Car *car;
    
    car = [Car new];
    [car print];
    
    return (0);
    
} // main


运行结果:

I am an engine. Vrooom!
I am a tire. I last a while.
I am a tire. I last a while.
I am a tire. I last a while.
I am a tire. I last a while.

 

转载于:https://www.cnblogs.com/davidgu/archive/2013/04/02/2995810.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值