黑马程序员-OC语言基础:面向对象语法 四

来源:互联网 发布:外企数据分析师 编辑:程序博客网 时间:2024/05/21 17:36

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

 

 

一、      继承

 

1.     继承的基本用法

l        设计两个类Bird、Dog

//Bird的声明

@interface Bird : NSObject

{

    @public

    int weight;

}

- (void)eat;

@end

//Bird的定义

@implementation Bird

- (void)eat {

    NSLog(@"吃吃吃-体重:%d", weight);

}

@end

// Dog的声明

@interface Dog : NSObject

{

    @public

    int weight;

}

- (void)eat;

@end

// Dog的定义

@implementation Dog

- (void)eat {

    NSLog(@"吃吃吃-体重:%d", weight);

}

@end

l        有相同的属性和行为,抽出一个父类Animal(先抽取weight属性,再抽取eat方法)

//Animal的声明

@interface Animal: NSObject

{

    @public

        int weight;

}

- (void)eat;

@end

//Animal的定义

@implementation Animal

- (void)eat {

   NSLog(@"吃吃吃-体重:%d", weight);

}

@end

l        子类在父类的基础上拓充属性和方法

//Bird的声明

@interface Bird : Animal

{

    @public

       int height;

}

- (void)fly;

@end

 

//Bird的定义

@implementation Bird

- (void)fly {

   NSLog(@"飞飞飞-高度:%d", height);

}

@end

 

// Dog的声明

@interface Dog : Animal

{

    @public

       int speed;

}

- (void)run;

@end

// Dog的定义

@implementation Dog

- (void)run {

   NSLog(@"跑跑跑-高度:%d", speed);

}

@end

l        子类方法和属性的访问过程:如果子类没有,就去访问父类的

l        父类被继承了还是能照常使用的

l        父类的静态方法

l        画继承结构图,从子类抽取到父类

l        NSObject的引出:全部OC类的最终父类,包含了一些常用方法,比如+new

 

2.     继承的专业术语

l        父类\超类  superclass

l        子类  subclass\subclasses

 

3.     继承的细节

l        单继承

l        子类和父类不能有相同的成员变量

l        方法的重写

 

4.     super关键字

l        分别调用父类的对象方法和类方法

 

5.     继承的好处

l        不改变原来模型的基础上,拓充方法

l        建立了类与类之间的联系

l        抽取了公共代码

l        坏处:耦合性强

 

6.     继承的使用场合

l        它的所有属性都是你想要的,一般就继承

l        它的部分属性是你想要的,可以抽取出另一个父类

 

 

二、      多态

 

1.  多态的基本概念

l        某一类事物的多种形态

l        OC对象具有多态性

 

2.  多态的体现

Person*p = [Student new];

p->age= 100;

[p walk];

l        子类对象赋值给父类指针

l        父类指针访问对应的属性和方法

 

3.  多态的好处

l        用父类接收参数,节省代码

 

4.  多态的局限性

l        不能访问子类的属性(可以考虑强制转换)

 

5.  多态的细节

l        动态绑定:在运行时根据对象的类型确定动态调用的方法

 

 

三、      NSString的简单使用

 

1.       字符串的快速创建

NSStirng *str = @“Hello”;

2.       使用静态方法创建

3.       使用%@输出字符串

NSString *name = @”mj”;

NSLog(@“我的名字是%@”,  name);

 

0 0