The three basic features of object-oriented are encapsulation, inheritance, and polymorphism. Encapsulation simply combines a set of data structures and related operations defined on them into a class, inheriting a parent-child relationship, child classes can have member variables, attributes, and methods defined by the parent class.
Polymorphism means that the member variables and methods defined in the parent class inherit from the quilt class, and the parent class objects can exhibit different behaviors. All methods in OC are virtual methods. When running, the pointer type is not used. The called method is determined based on the type of the generated object.
Taking transportation as an example, the parent class is defined as vehicle. The two subclasses, bicycle and car, all inherit from this class and have the member variable name, property height, and instance method run of the parent class.
“Vehicle.h”@interface Vehicle : NSObject{ NSString *name;}@property(assign, nonatomic)int weight;-(void)run;@end<span style="font-family:SimHei;">"Bicycle.h"</span>@interface Bicycle : Vehicle@end"Car.h"@interface Car : Vehicle@endRun methods in CAR and bicycle are implemented respectively.
@implementation Bicycle-(void)run{ [email protected]"自行车"; self.weight=100; NSLog(@"%@ %d", name , self.weight);}@end
@implementation Car-(void)run{ [email protected]"汽车"; self.weight=2000; NSLog(@"%@ %d", name, self.weight);}@end
Test in Main. m
#import <Foundation/Foundation.h>#import "Vehicle.h"#import "Car.h"#import "Bicycle.h"int main(int argc, const char * argv[]){ @autoreleasepool { Car *car=[[Car alloc]init]; Bicycle *bike=[[Bicycle alloc]init]; Vehicle *veh=car; [car run]; veh = bike; [veh run]; } return 0;}
Running result: Automotive 2000
Bicycle 100
Objective C Polymorphism