黑马程序员——继承

来源:互联网 发布:php date 格式化输出 编辑:程序博客网 时间:2024/05/22 06:56

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

继承:类B继承类A,会把类A的所有属性给类B

例:设计类
@interface Dog :NSObject
{
 年龄、体重
}
年龄的set、get方法
体重的set、get方法
@end

@implementation Dog

年龄的set、get方法的实现
体重的set、get方法的实现

@end

@interface Cat :NSObject
{
 年龄、体重
}
年龄的set、get方法
体重的set、get方法
@end

@implementation Cat

年龄的set、get方法的实现
体重的set、get方法的实现

@end

分析:猫和狗的声明和实现代码完全一样,只不过类名不同而已,这时,就要考虑用继承

#inport<Foundation/Foundation.h>//声明@interface Animal :NSObject{ int _age; double _weight;} -(void)setAge:(int)age;-(int)age;-(void)setWeight:(double)weight;-(double)weight;@end@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、Cat的父类,Dog、Cat称为Animal的子类@interface Dog :Animal@end@implementation Dog@end@interface Cat :Animal@end@implementation Cat@endint main(){ Dog * d = [Dog new]; [d setAge:10]; NSLog(@"age=%d",[d age]); return 0;}

输出结果:age=10

注:[Dog wnew]这是一个类调用,所以类是一个new方法,是NSObject中的类方法。
越往下继承,拥有的成员变量和方法越多,Animal只拥有NSObject的成员变量和方法,
而Dog、Cat不仅拥有NSObject的成员变量和方法,还拥有Animal的成员变量和方法。

继承的好处:
 1>抽取重复代码
 2>建立了类之间的关系
 3>子类拥有父类中的所有成员变量和方法

注意:基本上所有类的根类是NSObject

例2

#inport<Foundation/Foundation.h>//声明@interface Person :NSObject{ int _age;}-(void)setAge:(int)age;-(int)age;-(void)run;@end@implementation Person//方法的实现-(void)run{ NSLog(@"Person--跑");}-(void)setAge:(int)age{ _age = age;}-(int)age{ return _age;}@end@interface Student :NSObject{ int _no;}@end@implementation Student//方法的实现-(void)run{ NSLog(@"Student--跑");}@endint main(){ Student *s = [Student new]; [s run]; return 0; }


输出结果:Student--跑

调用[s run]时,先在Student中找run方法,有,输出,若Student中无-(void)run方法,则从Student的父类Person中找,
则会输出Person--跑,若无,再从NSObject中找。

1.不允许子类和父类有相同的成员变量
2.子类重新实现父类中的某方法称为重写
例如:例2中的run方法
重写会覆盖父类以前的做法
3.就像每个对象里都有一个isa指针指向生成它的类一样,每个类里都有一个superclass指针,指向它的父类
4.父类的声明必须在子类的前边
5.调用某个方法时,优先去当前类中找,找不到再去父类中找
6.其实,每个对象中都有isa指针的原因是:他们的共同父类NSObject里定义了成员变量
@interface NSObject<NSObject>
{
 class isa;
}
@end
7.若在父类中Person中声明和实现+(void)test
    {
       NSLog(@"111");
    }
在子类中Student中有+(void)test2
    {
      [self test];
    }
则main()中有
{
 [Student test2];
}

先在Student类中找test类方法,调[self test]相当于[Student test],在Student中找test类方法,
找不到,再到父类Person中找test类方法,有,所以最终输出:111

 


 

 

0 0
原创粉丝点击