------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
一、继承
eg:
#import <Foundation.Foundation.h>
@interface Animal : NSObject //声明一个Animal类,并且继承了NSObject
{
int _age; // 声明了两个成员变量
double _weight;
}
- (void)setAge:(int)age; //声明set方法
- (void)setWeight:(double)weight;
- int)age; //声明get方法
- (double)weight;
- (void)run;
@implementation Animal //类的实现
- (void)setAge:(int)age //set方法的实现
{
_age = age;
}
- (void)setWeight:(double)weight//set方法的实现
{
_weight = weight;
}
- int)age //get方法的实现
{
return _age;
}
- (double)weight //get方法的实现
{
return _weight;
}
- (void)run
{
NSLog(@"动物跑了起来");
}
@end
@interface Dog : Animal //Dog继承了Animal里面所有的成员变量和方法
@end
@implementation Dog
@end
int main()
{
Dog *d = [Dog new];
[d setAge:8];
[d setWeight:20.0];
NSLog(@"%岁的狗,%d公斤",[d age], [d weight]);
return 0;
}
5.重写
子类重新实现父类中某个方法,覆盖父类以前的做法
eg:
#import <Foundation.Foundation.h>
@interface Animal : NSObject //声明一个Animal类,并且继承了NSObject
{
int _age; // 声明了两个成员变量
double _weight;
}
- (void)setAge:(int)age; //声明set方法
- (void)setWeight:(double)weight;
- int)age; //声明get方法
- (double)weight;
- (void)run;
@implementation Animal //类的实现
- (void)setAge:(int)age //set方法的实现
{
_age = age;
}
- (void)setWeight:(double)weight//set方法的实现
{
_weight = weight;
}
- int)age //get方法的实现
{
return _age;
}
- (double)weight //get方法的实现
{
return _weight;
}
- (void)run
{
NSLog(@"动物跑了起来");
}
@end
@interface Dog : Animal //Dog继承了Animal里面所有的成员变量和方法
- (void)run;
@end
@implementation Dog
- (void)run //重写父类run方法
{
NSLog(@"%岁,%d公斤的狗跑了起来",[d age], [d weight]);
}
@end
int main()
{
Dog *d = [Dog new];
[d setAge:8];
[d setWeight:20.0];
[d run];
NSLog(@"%岁的狗,%d公斤",[d age], [d weight]);
return 0;
}
super关键字