继承的好处:
1> 抽取重复代码2> 建立了类之间的关系
3> 子类可以拥有父类中的所有成员变量和方法
注意点:
1> 基本上所有类的根类是NSObject
#import <Foundation/Foundation.h>
/********Animal的声明*******/
@interface Animal : NSObject
{
int _age;
double _weight;
}
- (void)setAge:(int)age;
- (int)age;
- (void)setWeight:(double)weight;
- (double)weight;
@end
/********Animal的实现*******/
@implementation Animal
- (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
- (void)setWeight:(double)weight
{
_weight = weight;
}
- (double)weight
{
return _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()
{
Dog *d = [Dog new];
[d setAge:10];
NSLog(@"age=%d", [d age]);
return 0;
}
重写:子类重新实现父类中的某个方法,覆盖父类以前的做法
注意:
1> 父类必须声明在子类的前面
2> 子类不能拥有和父类相同的成员变量
3> 调用某个方法时,优先去当前类中找,如果找不到,去父类中找
2.坏处:耦合性太强
#import <Foundation/Foundation.h>
// Person
@interface Person : NSObject
{
int _age;
}
- (void)setAge:(int)age;
- (int)age;
- (void)run;
+ (void)test;
@end
@implementation Person
+ (void)test
{
NSLog(@"Person+test");
}
- (void)run
{
NSLog(@"person---跑");
}
- (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
@end
// 不允许子类和父类拥有相同名称的成员变量
// Student
@interface Student : Person
{
int _no;
// int _age;
}
+ (void)test2;
@end
@implementation Student
// 重写:子类重新实现父类中的某个方法,覆盖父类以前的做法
- (void)run
{
NSLog(@"student---跑");
}
+ (void)test2
{
[self test];
}
@end
int main()
{
[Student test2];
// Student *s = [Student new];
//
// [s run];
return 0;
}