Understanding of OC polymorphism and oc Polymorphism
Key points:
1. Multiple forms, multiple types of references
A referenced variable can point to any class object.
For a reference to a parent class (there is an inheritance relationship between the class), you can point to the subclass or the class, pointing to different types.
When a message is sent to an object through this reference, the call methods are different. In this case, the call method is a polymorphism.
2. There is a relationship between classes and inheritance relationships between classes.
The reference of the parent class can point to the reference of the subclass or the reference of this class.
The reference of the parent class points to the subclass object and sends messages. The method of the subclass object is called.
The reference of the parent class points to the object of this class, sends messages, and CALLS methods of this class.
3. Compilation and runtime types
* Under polymorphism, the reference of the parent class can point to the reference of the subclass. during compilation, the compiler cannot determine the type of the object to be pointed, all compilers use references as parent class references for compilation checks.
* When calling a method, it is found that it is indeed a subclass object and creates space for the subclass type.
Animal * animal = [[Dog alloc] init];
During compilation, the Dog type is used as the Animal type for compilation. During running, the Dog type object is called.
Code Analysis:A is the parent class, B inherits A, C inherits B
A:
#import <Foundation/Foundation.h>@interface A : NSObject- (void)show;@end
#import "A.h"@implementation A- (void)show{ NSLog(@"A show");}@end
In B:
#import "A.h"@interface B : A- (void)show;@end
#import "B.h"@implementation B- (void)show{ NSLog(@"B show");}@end
C:
#import "B.h"@interface C : B-(void)show;@end
#import "C.h"@implementation C- (void)show{ NSLog(@"C show");}@end
In main. m
// A pointer to A type object A * a = [[A alloc] init]; [a show]; // polymorphism // The parent class Pointer Points to the subclass object B * B = [[B alloc] init]; // which method is called by B show? [B show]; // dynamic monitoring-the actual type of the object will be monitored when the method is called. // C * C = [[c alloc] init] is also the same as that of the object. [c show];
Output result:
A showB showC show