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