一 概述
OC中如果类A继承类B,B就成为A的父类。那么B的成员全部属于A的成员。相当于A全部拥有了B的所有成员(所有变量与所有方法)。即子类拥有父类中所有的成员变量和方法
二 继承的基本用法
2.1 设计两个类Bird,Dog
- Brid,Dog是两个OC类
- 两个类都有属性和方法(既有相似的,又有不同的)
- 以Bird和Dog抽取父类,并从父类继承
2.2 类的声明与定义
-
Brid类
// Bird的声明 @interface Bird : NSObject { @public int weight; } - (void)eat; @end // Bird的定义 @implementation Bird - (void)eat { NSLog(@"吃吃吃-体重:%d", weight); } @end
-
Dog类
@interface Dog : NSObject { @public int weight; } - (void)eat; @end // Dog的定义 @implementation Dog - (void)eat { NSLog(@"吃吃吃-体重:%d", weight); } @end
2.3 父类抽取
- 有相同的属性和行为,抽出一个父类Animal(先抽取weight属性,再抽取eat方法)
// Animal的声明
@interface Animal : NSObject
{
@public
int weight;
}
- (void)eat;
@end
// Animal的定义
@implementation Animal
- (void)eat {
NSLog(@"吃吃吃-体重:%d", weight);
}
@end
2.4 子类在父类的基础上扩充属性和方法
-
Bird类
// Bird的声明 @interface Bird : Animal { @public int height; } - (void)fly; @end // Bird的定义 @implementation Bird - (void)fly { NSLog(@"飞飞飞-高度:%d", height); } @end
-
Dog类
// Dog的声明 @interface Dog : Animal { @public int speed; } - (void)run; @end // Dog的定义 @implementation Dog - (void)run { NSLog(@"跑跑跑-高度:%d", speed); } @end
三 练习
#include <Foundation/Foundation.h>
@interface Person:NSObject
{
int _age;
}
-(void)setAge:(int)age;
-(int)age;
-(void)run;
@end
@implementation Person
-(void)setAge:(int)age
{
_age=age;
}
-(int)age
{
return _age;
}
-(void)run
{
NSLog(@"person----跑");
}
@end
@interface Student : Person
{
int _no;
//int _age;
}
@end
@implementation Student
-(void)run
{
NSLog(@"student----跑");
}
@end
int main()
{
Student *stu=[Student new];
[stu run];
return 0;
}
四 总结
4.1 概念
- 子类方法和属性的访问过程:如果子类没有,就去访问父类的
- 父类被继承了还是能照常使用的
- 父类的静态方法
- 画继承结构图,从子类抽取到父类
- NSObject的引出:全部OC类的最终父类,包含了一些常用的方法,比如+new
4.2 继承的好处
- 不改变原来模型的基础上,拓充方法
- 建立了类与类之间的联系
- 抽取了公共代码
4.3 继承的坏处
- 耦合性强
4.4 继承的使用场合
- 它的所有属性都是你想要的,一般就继承
- 它的部分属性是你想要的,可以抽取出另一个父类