OC之继承

来源:互联网 发布:ae软件破解版 编辑:程序博客网 时间:2024/06/05 18:05

#import<Foundation/Foundation.h>

/*

 1、继承的好处:

 1抽取重复代码

 2建立了类之间的关系

 3子类可以拥有父类中的所有成员变量和方法

 2、注意点

 1基本上所有类的根类是NSObject

 */

 

 

/********Animal的声明*******/

@interfaceAnimal : NSObject

{

    int _age;

    double _weight;

}

 

-(void)setAge:(int)age;

-(int)age;

 

-(void)setWeight:(double)weight;

-(double)weight;

@end

 

/********Animal的实现*******/

@implementationAnimal

-(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*******/

@interfaceCat : Animal

@end

 

@implementationCat

@end

 

intmain()

{

    Dog *d = [Dog new];

    [d setAge:10];

    NSLog(@"age=%d", [d age]);

    return 0;

}

super的作用

 1.直接调用父类中的某个方法

 2.super处在对象方法中,那么就会调用父类的对象方法

   super处在方法中,那么就会调用父类的类方法

[super walk];//直接调用父类的walk方法

  3.使用场合:子类重写父类的方法时想保留父类的一些行为

0 0
原创粉丝点击