首页 > 代码库 > Objective-C语言继承性

Objective-C语言继承性

• 继承性是面向对象的重要概念之一,子类能够继承父类的某些方法和成员变量。作用域限定符为private 的成员变量是不可以被继承的。子还可以重写父类的方法。

• 继承是单继承,要多继承引入了协议

•子类定义了和父类相同的成员变量,会把父类的成员变量屏蔽掉

• 为了了解继承性,我们看看这样的一个场景:一位面向对象的程序员小赵,在编程过程中需要描述和处理个人信息,于是他定义了类Person。

@interface Person: NSObject {NSString* name;int age;NSDate birthDate;}-(NSString*) getInfo;@end

而一周以后,小赵又遇到了新的需求,需要描述和处理学生信息,于是他又定义了一个新的类Student。

@interface Student : NSObject {NSString* name;int age;NSDate birthDate;NSString* school;}-(NSString*) getInfo;@end

Student和Person两个类的结构太接近了,后者只比前者多出一个属性school,却要重复定义其它所有的内容。Objective-C提供了解决类似问题的机制,那就是类的继承。

@interface Student : Person {NSString* school;}

子类不能继承父类中作用域限定符为@private 的成员变量。子类可以重写父类的方法,及命名与父类同名的成员变量。下面通过一个矩形类和正方形类的实例说明方法重写问题。

#import <Foundation/NSObject.h>@interface Rectangle: NSObject {int width;int height;}-(Rectangle*) initWithWidth: (int) w height: (int) h;-(void) setWidth: (int) w;-(void) setHeight: (int) h;-(void) setWidth: (int) w height: (int) h;-(int) width;-(int) height;-(void) print;@end
#import "Rectangle.h”@implementation Rectangle-(Rectangle*) initWithWidth: (int) w height: (int) h {self = [super init];if ( self ) {[self setWidth: w height: h];}return self;}-(void) setWidth: (int) w {width = w;}-(void) setHeight: (int) h {height = h;}... ...

-(void) setWidth: (int) w height: (int) h {
width = w;
height = h;
}
-(int) width {
return width;
}
-(int) height {
return height;
}
-(void) print {
printf( "width = %i, height = %i", width,
height );
}
@end

#import "Rectangle.h"@interface Square: Rectangle
-(Square*) initWithSize: (int) s;-(void) setSize: (int) s;-(int) size;@end
#import "Square.h"@implementation Square-(Square*) initWithSize: (int) s {self = [super init];if ( self ) {[self setSize: s];}return self;}-(void) setSize: (int) s {width = s;height = s;}... ...-(int) size {return width;}-(void) setWidth: (int) w {[self setSize: w];}-(void) setHeight: (int) h {[self setSize: h];}@end
#import <Foundation/Foundation.h>#import "Square.h"#import "Rectangle.h"int main (int argc, const char * argv[]) {Rectangle *rec = [[Rectangle alloc] initWithWidth: 10 height: 20];Square *sq = [[Square alloc] initWithSize: 15];NSLog(@"Rectangle: " );[rec print];NSLog(@"Square: " );[sq print];[sq setWidth: 20];NSLog(@"Square after change: " );[sq print];[rec release];[sq release];return 0;}

运行结果

Rectangle:width = 10, height = 20Square:width = 15, height = 15Square after change:width = 20, height = 20

 

Objective-C语言继承性