#import<Foundation/Foundation.h>
/*
继承的好处:
1.抽取重复代码
2.建立了类之间的关系
子类可以拥有父类中的所有成员变量和方法
*/
//Animal的声明
@interface Animal : NSObject
{
int _age;
double _weight;
}
- (void)setAge:(int) age;
- (int)age;
- (void)setWeight:(double)weight;
- (double)weight;
@end
//Aminal的实现
@implementation Animal
- (void)setAge:(int) age
{
_age = age;
}
- (int)age
{
return _age;
}
- (void)setWeight:(double)weight
{
_weight = weight;
}
- (double)weight
{
return _weight;
}
@end
//:Animal 继承了Animal,相当于拥有了Animal里面的所有成员变量和方法
//Animal 成为Dog的父类
//Dog成为Animal的子类
@interface Dog : Animal
@end
@implementation Dog
@end
//Cat
@interface Cat : Animal
@end
@implementation Cat
@end
int main()
{
Dog *d = [[Dog alloc] init];
[d setAge:10];
NSLog(@"age=%d", [d age]);
return 0;
}
objective-c 继承1
最新推荐文章于 2024-07-31 09:40:36 发布