Iphone开发(3) 一个使用组合的简单例子

#import <Foundation/Foundation.h>//导入文件有两种方式:#import" "和#import<>,第一种代表引入你自己的文件,第二种代表引入系统的文件

//文件的引用:在接口文件中,使用@class;在实现文件中,使用#import

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

@interface Tire : NSObject
@end


@implementation Tire

- (NSString *) description//此方法类似于Java里面的toString
{
    return (@"I am a tire. I last a while");
}

@end



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

@interface Engine : NSObject
@end


@implementation Engine

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

@end


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

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

- (void) print;

@end


@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);
	
}

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

@end 


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

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



你可能感兴趣的:(java,iPhone,Class,import,interface)