Objective-C 继承学习笔记

// All about Triangles

@interface Triangle : Shape
{
}

@end // Triangle


@implementation Triangle

- (void) draw
{
	NSLog (@"drawing a triangle at (%d %d %d %d) in %@",
		   bounds.x, bounds.y, 
		   bounds.width, bounds.height,
		   colorName(fillColor));
} // draw

@end // Triangle




// --------------------------------------------------
// All about Circles

@interface Circle : Shape
{
}

@end // Circle


@implementation Circle

- (void) draw
{
	NSLog (@"drawing a circle at (%d %d %d %d) in %@",
		   bounds.x, bounds.y, 
		   bounds.width, bounds.height,
		   colorName(fillColor));
} // draw

@end // Circle

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

关于继承的语法格式

在上文中类与方法的学习当中已经有了关于Shape类的声明。

要使我们的类从Shape类中继承而来。

只需将接口代码更改为

@interface Circle : Shape

@end //Circle

实例变量由Shape类继承,此时花括号可以省略。

方法调用先搜索当前类,再搜索超类(父类)。

对于本代码,搜索的方向大致为Circle->Shape->NSObject

对于每个子类draw实现不同,称为方法的重写。

// All about Circles

@interface Circle : Shape

@end // Circle


@implementation Circle

// I'm new!
- (void) setFillColor: (ShapeColor) c
{
	if (c == kRedColor) {
		c = kGreenColor;
	}
	
	[super setFillColor: c];
	
} // setFillColor


- (void) draw
{
	NSLog (@"drawing a circle at (%d %d %d %d) in %@",
		   bounds.x, bounds.y, 
		   bounds.width, bounds.height,
		   colorName(fillColor));
} // draw

@end // Circle




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

关于super重写方法的实现同时调用超类中的实现方式。

向super发送信息,即是向该类的超类发送信息,同理方法调用,先搜索超类,再搜索超类的超类等。

该代码中先检测颜色是否为红,如果是则改为绿色,再调用超类的方法,从而将fillColor由红色改为绿色。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章