现在的位置: 首页 > 综合 > 正文

oc 继承性

2017年10月24日 ⁄ 综合 ⁄ 共 2136字 ⁄ 字号 评论关闭

继承概念


继承性是面向对象的重要概念之一,子类能够继承父类的某些方法和成员变量。作用域限定符为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 的成员变量 。子类可以重写父类的方法,及命名与父类同名的成员变量 。下面通过一个矩形类和正方形类的实例说明方法重写问题。

Rectangle.h文件:

#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

Rectangle.m文件:

#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

Square.h文件:

#import "Rectangle.h"
@interface Square: Rectangle
-(Square*) initWithSize: (int) s;
-(void) setSize: (int) s;
-(int) size;
@end

Square.m文件:

#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

调用的main函数:

#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 = 20
Square:
width = 15, height = 15
Square after change:
width = 20, height = 20


抱歉!评论已关闭.