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由紅色改爲綠色。

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