前面学习的时候知道继承是两个类之间的关系。
一个项目可能会有很多部分组成。我们如何能更好的把他们组合在一起呢?我们认为在对象之间的才称之为composition.
就像一辆汽车由发动机和四个轮子组成。这样我们可以理解为一个汽车类由一个发动机类和轮子类组成。只有有了发动机和轮子才能有车子。所以我们要先创建轮子和发动机。
@interface Tire : NSObject
@end
@implementation Tire
-(NSString *) description
{
return (@"I am a tire.I last a while.");
}
@end
@interface Engine : NSObject
@end
@implementation Engine
-(NSString *) description
{
return (@"I am a engine, Vrooom!");
}
@end
@interface Car : NSObject {
@private
Engine *engine;
Tire *tires[4];
}
-(void) setEngine:(Engine *) newEngine;
-(Engine *) Engine;
-(void) setTire:(Tire *) tire atindex:(int)index;
-(Tire *) tireatIndex :(int) index;
-(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;
}
-(void) setEngine:(Engine *)newEngine
{
engine = newEngine;
}
-(Engine *)Engine
{
return engine;
}
-(void) setTire:(Tire *)tire atindex:(int)index
{
if(index<0||index>3)
{
NSLog(@"bad index %d in setTire:atindex:",index);
exit(1);
}
tires[index]=tire;
}
-(Tire *)tireatIndex:(int)index
{
if(index<0||index>3)
{
NSLog(@"bad index %d in setTire:atindex:",index);
exit(1);
}
return tires[index];
}
-(void) print
{
NSLog(@"%@",engine);
NSLog(@"%@", tires[0]);
NSLog(@"%@", tires[1]);
NSLog(@"%@", tires[2]);
NSLog(@"%@", tires[3]);
}
@end
然后我们在main函数中实例化车类。
实例化车类 Car *car =[Car new]; 而c# 实例化是 Car car = new Car;
调用车类中的方法[car print]; 调用方法是 car.print();
轮子和发动机都有很多种,但是他们都是轮子和发动机,所以具体的轮子和发动机继承他们相应的类。
@interface AllWeatherRadial : Tire
@end
@implementation AllWeatherRadial
-(NSString *) description
{
return (@"I am a tire for rain or shine");
}
@end
@interface AllWeatherRadial : Tire
@end
@implementation AllWeatherRadial
-(NSString *) description
{
return (@"I am a tire for rain or shine");
}
@end
int main (int argc, const char * argv[])
{
Car *car=[Car new];
//Engine *engine =[Engine new];
Engine *engine =[Slant6 new];
[car setEngine:engine];
for (int i=0 ; i<4; i++) {
//Tire *tire=[Tire new];
Tire *tire=[AllWeatherRadial new];
[car setTire:tire atindex:i];
}
[car print];
return 0;
}
1.set 和get方法就是用来读取数据来用的,常用在set方法的时候用set做为前缀,但是get方法时,不常用get方法做为前缀,因为在object-c里面get方法会认为当作参数传入的指针来返回数值。
2.init方法,中的if判断这么做是为了防止超类在初始化过程中返回的对象不同于原先创建的对象。