Objective - C基础: 第二天 - 8.继承的初体验
OC语言里的三大特点分别是封装, 继承, 多态, 在前面我们已经讲过封装思想了, 怎么去运用得需要看个人的修行, 现在我们来讲解继承~~
在我们日常生活中也有继承一说, 比如你继承了某人的财产, 你继承了你父母的基因, 你继承了某人的意志(出自火影忍者)等等, 那么在OC上也是同理, 让我们来看一个例子:
#import <Foundation/Foundation.h> @interface Man : NSObject { int _height; double _weight; } - (void)setHeight:(int)height; - (int)height; - (void)setWeight:(double)weight; - (double)weight; @end @implementation Man - (void)setHeight:(int)height { _height = height; } - (int)height { return _height; } - (void)setWeight:(double)weight { _weight = weight } - (double)weight { return _weight; } @end @interface Women : NSObject { int _height; double _weight; } - (void)setHeight:(int)height; - (int)height; - (void)setWeight:(double)weight; - (double)weight; @end @implementation Women - (void)setHeight:(int)height { _height = height; } - (int)height { return _height; } - (void)setWeight:(double)weight { _weight = weight } - (double)weight { return _weight; } @end int main() { return 0; }
按照我们之前所学的, 如果我们要设计两个类, 就必须和上面的例子一样, 写那么多的代码, 非常的繁琐, 看着都恶心, 为了解决这样的问题, 继承语法诞生了, 让我们继续往下看:
#import <Foundation/Foundation.h> /**********Person的声明**********/ @interface Person : NSObject { int _height; double _weight; } - (void)setHeight:(int)height; - (int)height; - (void)setWeight:(double)weight; - (double)weight; @end /**********Person的实现**********/ @implementation - (void)setHeight:(int)height { _height = height; } - (int)height { return _height; } - (void)setWeight:(double)weight { _weight = weight } - (double)weight { return _weight; } @end /**********Man**********/ @interface Man : NSObject @end @implementation Man @end /**********Women**********/ @interface Women : NSObject @end @implementation Women @end int main() { return 0; }
创建一个新的类, 把他们之间相同的变量, 方法抽出来, 放到新的类里面去, 那么我们如何继承呢? 下面来看看:
/**********Man**********/ @interface Man : Person @end @implementation Man @end /**********Women**********/ @interface Women : Person @end @implementation Women @end
在OC中, " : "号就是继承的意思, 左边是继承的类名, 右边是被继承的类名, 在这里, 左边的类我们称为子类, 右边的类我们称为父类, 一旦子类继承了父类, 那么子类就会拥有父类的所有变量以及方法, 下面让我们来验证一下是否正确:
@interface Man : Person @end @implementation Man @end @interface Women : Person @end @implementation Women @end int main() { Person *man = [Person new]; [man setHeight:160]; NSLog(@"身高 = %d", [man height]); return 0; }
输出的结果:
Cain:2.第二天 Cain$ cc 11-继承.m -framework Foundation Cain:2.第二天 Cain$ ./a.out 2015-01-18 11:39:18.263 a.out[16694:1811266] 身高 = 160
PS: A类继承了B类, 那么B类就是A类的父类, 而A类就是B类的子类, 如果还有类继承了A类, 那么该类就是A类的子类, 是B类的子孙类, 以此类推, 而我们一直所写的NSObject是系统自带的类, 这个是必须的继承的, 不然就没法使用系统自带的方法, 而NSObject这种类, 我们称为基类, 也叫做根类.
下面让我们来看看示意图:
1.继承的好处:
1> 抽取重复代码
2> 建立了类之间的关系
3> 子类可以拥有父类中的所有成员变量和方法
2.注意点
1> 基本上所有类的根类是NSObject
好了, 这次我们就到这里, 下次我们继续~~~~