继承
#import
*******Animal的声明******
@interface Animal : NSObject
{
}
- (void)setAge:(int)age;
- (int)age;
- (void)setWeight:(double)weight;
- (double)weight;
@end
*******Animal的实现******
@implementation Animal
- (void)setAge:(int)age
{
}
- (int)age
{
}
- (void)setWeight:(double)weight
{
}
- (double)weight
{
}
@end
*******Dog******
Animal 继承了Animal,相当于拥有了Animal里面的所有成员变量和方法
Animal称为Dog的父类
Dog称为Animal的子类
@interface Dog : Animal
@end
@implementation Dog
@end
*******Cat******
@interface Cat : Animal
@end
@implementation Cat
@end
int main()
{
}
==================================================
继承
Person
@interface Person : NSObject
{
}
- (void)setAge:(int)age;
- (int)age;
- (void)run;
+ (void)test;
@end
@implementation Person
+ (void)test
{
}
- (void)run
{
}
- (void)setAge:(int)age
{
}
- (int)age
{
}
@end
Student
@interface Student : Person
{
}
+ (void)test2;
@end
@implementation Student
// 重写:子类重新实现父类中的某个方法,覆盖父类以前的做法
- (void)run
{
}
+ (void)test2
{
}
@end
int main()
{
}
==================================================
继承的使用场合
1.继承的使用场合
继承:xx 是 xxx
组合:xxx 拥有 xxx
@interface Score : NSObject
{
}
@end
@implementation Score
@end
@interface Student : NSObject
{
}
@end
@implementation Student
@end
本文深入探讨了继承在面向对象编程中的好处与注意事项,包括抽取重复代码、建立类间关系、重写方法等,并通过实例展示了继承的使用场景与效果。同时,介绍了继承的坏处以及如何避免耦合性过强的问题。
484

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



