I. Basic CONCEPTS
Polymorphism is based on inheritance, and polymorphism allows a pointer to the parent class to point to the object of the subclass.
If you use a parent class type in a function or parameter, you can pass in the parent class, the child class object, but a variable of the parent class type cannot directly invoke a method that is unique to the subclass.
Declaration and implementation of the animal class
// Animal @interface animal:nsobject-(void) eat; @end @implementation Animal-(void) eat{ NSLog (@ "animal-eats something----");} @end
The dog class inherits from the Animal class
// Dog @interface dog:animal-(void) run; @end @implementation Dog-(void) run{ NSLog (@ "Dog---run up ");} // override animal's Eat method -(void) eat{ NSLog (@ "dog-eat---- ");} @end
#import <Foundation/Foundation.h>//Animal@interface Animal:nsobject- (void) Eat, @end @implementation Animal- (void) eat{NSLog (@"animal-eat something----");} @end//Dog@interface Dog:animal- (void) run; @end @implementation Dog- (void) run{NSLog (@"Dog---running.");}- (void) eat{NSLog (@"dog-eat something----");} @end//if the parent class type is used in the argument, you can pass in the parent class, the child class objectvoidFeed (Animal *a) {[A eat];}intMain () {//Polymorphic : Parent class pointer to child class objectAnimal *a = [DogNew]; //The object's true image is detected when the method is called[a eat]; return 0;}
Result: dog-eating----
Two. Multi-state summary
- No inheritance, no polymorphism.
- The embodiment of the code: a pointer to the parent class type points to the subclass object
- Benefit: If you are using a parent class type in a function \ method parameter, you can pass in the parent class, the child class object
- Limitation: A variable of a parent class type cannot directly invoke a method specific to a subclass. You must strongly convert to a subclass type variable to directly invoke a method that is specific to a subclass class
Multi-state of the three major features of OC