黑马程序员技术交流社区
标题:
每日小结:继承
[打印本页]
作者:
崔石炫
时间:
2014-9-25 03:01
标题:
每日小结:继承
参考以下代码:
#import <Foundation/Foundation.h>
@interface Person : NSObject//Person类,表示人,拥有_age和_weight 2个属性,继承自NSObject
{
@public
int _age;
double _weight;
}
@end
@interface GoodStudent : Person// GoodStudent类,表示学生,继承自Person类
{
@public
int _mathScore; // GoodStudent类拥有Person类的_age和_weight 2个属性
int _OCScore; // 此外,GoodStudent类还拥有自己的3个属性
int _ChineseScore;
}
@end
@interface Score : NSObject // Score类,表示分数,拥有_mathScore、_OCScore和_ChineseScore 3个属性,继承自NSObject
{
@public
int _mathScore;
int _OCScore;
int _ChineseScore;
}
@end
@interface BadStudent : Score // BadStudent类,表示学生,继承自Score类,拥有Score类的3个属性
{
@public // 此外,BadStudent类还拥有自己的_age和_weight 2个属性
int _age;
double _weight;
}
@end
int main()
{
GoodStudent *goodStu = [GoodStudent new];
goodStu->_age = 10;
goodStu->weight = 56.2;
goodStu->_mathScore = 98;
goodStu->_OCScore = 88;
goodStu->_ChineseScore = 96;
BadStudent *badStu = [BadStudent new];
badStu->_age = 10;
badStu->weight = 56.2;
badStu->_mathScore = 98;
badStu->_OCScore = 88;
badStu->_ChineseScore = 96;
NSLog(@”goodStu--> age:%d , weight:%f kg , mathScore:%d , OCScore:%d , ChineseScore:%d” , goodStu->_age , goodStu->weight , goodStu->_mathScore , goodStu->_OCScore , goodStu->_ChineseScore);
NSLog(@” badStu--> age:%d , weight:%f kg , mathScore:%d , OCScore:%d , ChineseScore:%d” , badStu->_age , badStu->weight , badStu->_mathScore , badStu->_OCScore , badStu->_ChineseScore);
return 0;
}
复制代码
作者:
崔石炫
时间:
2014-9-25 03:02
解析:
上述代码中,GoodStudent继承自Person类,除去自身声明中的3个属性,还拥有父类Person中的2个属性;BadStudent继承自Score类,出去自身声明中的2个属性,还拥有父类Score中的3个属性。
main函数中对GoodStudent类的goodStu对象的属性进行赋值操作,并对BadStudent类的badStu对象的属性进行相同的赋值操作,然后用NSLog打印出两个对象的各属性值,输出结果相同。
以上两种方案都能实现功能,并且结果相同。
继承的好处:
1.抽取重复代码,父类已有的属性和方法,子类不需要再次声明和实现,达到精简代码的目的。
2.建立类和类之间的关系,比如GoodStudent类是Person类的子类,即:GoodStudent是Person。
对于BadStudent类,此类继承自Score类,虽然同样精简了代码,但是BadStudent类与Score类的关系不如GoodStudent类与Person类的关系那样恰当,不能说BadStudent是Score。
考虑下面的Student类:
@interface Student : Person
{
@public
Score *_score;
}
@end
复制代码
这个Student类继承自Person类,拥有Person类的_age和_weight属性,同时自身组合了一个Score类对象。
这种方案不但使代码更加精简,而且以更恰当的方式模拟了自然界对象与对象之间的关系:
Student是Person,且拥有Score。
编码过程中应当适时抽取重复代码,以精简的代码实现功能,便于日后维护。但是,不能一味使用继承来精简代码,滥用继承会造成代码耦合性太强,对后期维护不利,而要在适当的时候选用继承和组合并用的方式。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2