OC语法 子类与父类

2014年08月10日15:54:35

1,子类拥有父类所有的东西,因此可以在子类里面直接使用父类声明的实体变量或方法而无需再次声明。

2,子类如果重写了父类里面的方法则子类的对象在调用时会调用子类里的,而不再是父类里的方法。

3,父类的对象不能调用子类的方法。

4,父类的指针可以指向子类的对象,这个指针调用方法时将调用子类的方法(如果重写了的话)而不是父类里的方法,而子类的指针却不可以指向父类的对象。

下面为例子:(Human.h/m和Studen.h/m未上传)其中Student:Human

//
//  main.m
//  Test
//
//  Created by apple  on 14-8-10.
//  Copyright (c) 2014年. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Human.h"
#import "Student.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        Human *human = [[Human alloc]init];
        Student *student = [[Student alloc]init];
        
        Human *h1 = student;
        
        [student print];
        
        [student setAge:20];
        [student setHeigt:168];
        NSLog(@"height= %f,age = %d,h1:age=%d",[student Height],[student Age],[h1 Age]);
        
        
        [human print];
        NSLog(@"height= %f,age = %d",[human Height],[human Age]);
    }
    return 0;
}
输出如下:

2014-08-10 15:49:35.249 Test[29651:303] this is Student class:
2014-08-10 15:49:35.450 Test[29651:303] obtain height:use the method of Student!
2014-08-10 15:49:35.452 Test[29651:303] obtain age:use the method of Student!
2014-08-10 15:49:35.452 Test[29651:303] obtain age:use the method of Student!
2014-08-10 15:49:35.453 Test[29651:303] height= 168.000000,age = 20,h1:age=20
2014-08-10 15:49:35.453 Test[29651:303] this is Human class:
2014-08-10 15:49:35.454 Test[29651:303] obtain height:use the method of Human!
2014-08-10 15:49:35.455 Test[29651:303] obtain age:use the method of Human!
2014-08-10 15:49:35.455 Test[29651:303] height= 0.000000,age = 0
Program ended with exit code: 0

可以看出即使student对象对height和age设定了值,但NSLog(@"height= %f,age = %d",[human Height],[human Age]);

输出2014-08-10 15:49:35.454 Test[29651:303] obtain height:use the method of Human!
2014-08-10 15:49:35.455 Test[29651:303] obtain age:use the method of Human!
2014-08-10 15:49:35.455 Test[29651:303] height= 0.000000,age = 0

即父类的对象human还是调用的父类里的方法Height,而不是子类的。由于父类里并没有给height赋值因此,[human Height] height值为0.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值