面向对象的三大特性:封装、继承、多态
假如说·现在有个例子狮子吃动物;
现有狮子类。
#import <Foundation/Foundation.h>
@class Animal;
@interface Lion : NSObject
- (void)eatAnimal:(Animal *)animal;
//形参是父类的对象指针,可以传子类对象的地址
@end
.m文件
@implementation Lion
- (void)chaseAnimal:(Animal *)animal
{
NSLog(@"狮子追%@", [animal class]);
//打印对象的类名
[animalbeChasen];//动物被追
//子类的方法都是重写父类的方法,接口同一。
}
@end
现有动物Animal类,羚羊Antelope类,鹿Deer类
@interface Animal : NSObject
- (void)beChasen; //被追后的响应
@end
羚羊Antelope类
.h文件
@interface Antelope :Animal
@end
.m文件
@implementation Antelope
- (void)beChasen
{
NSLog(@"Antelope大叫着跑开");
}
@end
鹿Deer类
.h文件
@interface Deer: Animal
@end
.m文件
@implementation Deer
- (void)beChasen
{
NSLog(@"Deer受伤了,只好希望狮子没有看见它!");
}
@end
Lion * lion = [[Lionalloc] init];
Deer *deer = [[Deeralloc] init];
Antelope * antelope = [[Antelopealloc] init];
[lion chaseAnimal:deer];
[lion chaseAnimal:antelope];
这里Lion的方法参数Animal类,Deer,Antelope类的父类
但是同一个方法,参数指针指向的是子类产生不同的效果
在程序需要扩展时,只要满足继承Animal类,都可以作为参数传进去,当然前提是你必须继承Animal类,重写Animal类中的方法
注意
不允许子类和父类拥有相同名称的成员变量
子类调用方法,首先去子类去找,找不到再去去父类
6050

被折叠的 条评论
为什么被折叠?



