One of the important purposes of inheritance is to achieve polymorphism. Now let's take a look at OC inheritance.
First, inheritance
Parent class:
Header file
1 //2 //Peason.h3 //01-Inheritance and polymorphism4 //5 //Created by zhangjing on 15/7/5.6 //Copyright (c) 2015 zhangjing. All rights reserved.7 //8 9 #import<Foundation/Foundation.h>Ten One @interfacePeason:nsobject A@property NSString *name; -@propertyintAge ; - the-(ID) Initwithname: (nsstring*) name Age: (int) age; --(void) Say; - @end
Implementation file:
1 //2 //peason.m3 //01-Inheritance and polymorphism4 //5 //Created by zhangjing on 15/7/5.6 //Copyright (c) 2015 zhangjing. All rights reserved.7 //8 9 #import "Peason.h"Ten One @implementationPeason A @synthesizeName=_name; - @synthesizeAge=_age; --(ID) Initwithname: (nsstring*) name Age: (int) Age the { -peason* p=[[Peason alloc]init]; -P.name=name; -P.age=Age ; + returnp; - } +-(void) Say A { atNSLog (@"%@_____%@", self,self.name); - } - @end
Sub-class:
Header file
1 //2 //Student.h3 //01-Inheritance and polymorphism4 //5 //Created by zhangjing on 15/7/5.6 //Copyright (c) 2015 zhangjing. All rights reserved.7 //8 9 #import "Peason.h"Ten One @interfaceStudent:peason A-(ID) Initwithname: (nsstring*) name Age: (int) age; --(void) Say; - @end
Implementation file
1 //2 //STUDENT.M3 //01-Inheritance and polymorphism4 //5 //Created by zhangjing on 15/7/5.6 //Copyright (c) 2015 zhangjing. All rights reserved.7 //8 9 #import "Student.h"Ten One @implementationStudent A-(void) Say - { -NSLog (@"My name is%@. I am student.", self.name); the } --(ID) Initwithname: (nsstring*) name Age: (int) Age - { -student* s=[[Student alloc]init]; +S.name=name; -S.age=Age ; + returns; A } at @end
Calling functions
1 //2 //main.m3 //01-Inheritance and polymorphism4 //5 //Created by zhangjing on 15/7/5.6 //Copyright (c) 2015 zhangjing. All rights reserved.7 //8 9 #import<Foundation/Foundation.h>Ten #import "Peason.h" One #import "Student.h" A - intMainintargcConst Char*argv[]) { - @autoreleasepool { thepeason* P=[[peason Alloc]initwithname:@"Tom"Age: -]; - [P Say]; -student* s=[[student Alloc]initwithname:@"Jack"Age: A]; - [s Say]; + } - return 0; +}
Output Result:
2015-07-05 15:32:51.221 01- Inheritance and polymorphism [1281:44755] <peason:0x100206a30>_____tom
2015-07-05 15:32:51.222 01- Inheritance and polymorphism [1281:44755] My name is Jack. I am student.
Note: If the subclass wants to use the same initialization method as the parent class, then it needs to be rewritten again, and if you don't rewrite the initialization method that uses the parent class directly, you get the object of a parent class.
oc--inheritance