Objective

在前面, 我们知道了继承的基本认识, 那继承有什么使用注意呢? 又可以怎样组合呢? 下面让我们一起来看看~~


例子:

#import <Foundation/Foundation.h>
/**********Person类声明**********/
@interface Person : NSObject
{
    int _weight;
    double _height;
}
- (void)setWeight:(int)weight;
- (int)weight;

- (void)setHeight:(double)height;
- (double)height;

- (void)test;
@end

/**********Person类实现**********/
@implementation Person
- (void)setWeight:(int)weight
{
    _weight = weight;
}
- (int)weight
{
    return _weight;
}

- (void)setHeight:(double)height
{
    _height = height;
}
- (double)height
{
    return _height;
}

- (void)test
{
    NSLog(@"哈哈哈");
}
@end


@interface Student : Person
@end

@implementation Student
@end


int main()
{
    Student *stu = [Student new];
    [stu test];
    return 0;
}

这是我们运用之前所学的知识设计的一个类, 这样的类非常的正常, 那如果改一下:

@interface Student : Person
{
    int _weight;
    double _height;
}
@end

编译链接结果:

12-继承.m:46:9: error: duplicate member '_weight'
    int _weight;
        ^
12-继承.m:5:9: note: previous declaration is here
    int _weight;
        ^
12-继承.m:47:12: error: duplicate member '_height'
    double _height;
           ^
12-继承.m:6:12: note: previous declaration is here
    double _height;
           ^
2 errors generated.

在继承的使用中, 子类不能有和父类相同的变量名, 哪怕你的类型不一样也不可以, 编译器会报错.



既然如此, 那么继承里面可以使用同名方法么? 下面让我们来看看:

@interface Student : Person

- (void)test;
<pre name="code" class="objc">
@end
@implementation Student- (void)test{ NSLog(@"嘿嘿嘿");}@end


编译链接结果:

Cain:2.第二天 Cain$ cc 12-继承.m -framework Foundation
Cain:2.第二天 Cain$ ./a.out 
2015-01-18 14:14:43.699 a.out[16968:1845511] 嘿嘿嘿

答案是可以的, 但会有就近原则, 当Student没有这个方法的时候才会去父类里找这个方法.



那如果, 我在Person里不实现test方法, 只是做声明, 而在Student里只做实现, 不做声明呢?

@interface Person : NSObject
{
    int _weight;
    double _height;
}
- (void)setWeight:(int)weight;
- (int)weight;

- (void)setHeight:(double)height;
- (double)height;

- (void)test;

@end

@implementation Student
- (void)test
{
    NSLog(@"嘿嘿嘿");
}
@end

运行结果看看:

Cain:2.第二天 Cain$ cc 12-继承.m -framework Foundation
12-继承.m:18:17: warning: method definition for 'test' not found [-Wincomplete-implementation]
@implementation Person
                ^
12-继承.m:14:1: note: method 'test' declared here
- (void)test;
^
1 warning generated.

Cain:2.第二天 Cain$ ./a.out 
2015-01-18 14:29:37.027 a.out[16998:1849876] 嘿嘿嘿

虽然在运行的时候会有警告, 运行的时候出来的答案是正确的~~~


子类中重新实现父类的某个方法, 覆盖了父类以前的做法, 我们称为重写.



注意事项:

1.注意

1> 父类必须声明在子类的前面

2> 子类不能拥有和父类相同的成员变量

3> 调用某个方法时,优先去当前类中找,如果找不到,去父类中找

 

 2.坏处:耦合性太强(所谓的耦合性, 就是一个子类继承与父类, 如果父类被删掉了, 那么子类就无法进行正常工作.)




好了, 这次我们就讲到这里, 下次我们继续~~~~

原文地址:https://www.cnblogs.com/iOSCain/p/4282848.html