First, the basic concept
Polymorphism in the code embodiment, that is, a variety of forms, must have inheritance, no inheritance is not polymorphic.
When polymorphic is used, dynamic detection is performed to invoke the real object method.
Polymorphism in code is the embodiment of the parent class pointer to the subclass object.
Declaration of the Animal class
Implementation of the Animal class
The dog class inherits from the Animal class
The implementation of the Dog class
Test procedure:
Second, the use of attention
Code Analysis:
Dog *d=[[animal alloc] init]; Animal is a dog? Is the semantics correct?
NSString *str=[dog New]; Dog is a string? Is it correct?
OC language is a weak grammar of the language, compile time and will not error, so this requires us in the actual development process must follow the established specifications to write code, do not appear that the dog is a string such problems.
Benefits of Polymorphism:
A new function is needed to feed the dog.
Void Feed (Dog *d)
{
[D eat];
}
If you need to feed the cat at this time, you should rewrite a new function
Void Feed (Cat *c)
{
[C Eat];
}
Dogs and cats, in fact, inherit from the animal class, where polymorphism can be used to simplify the code.
Only the parameters of the function are written in the animal * type, so both the dog and cat type objects can be passed in.
You can change the parameters directly when you call them.
Polymorphism limitations: Pointer variables of a parent class type cannot directly invoke methods that are specific to subclasses.
Non-Recommended Practice ~
Animal *a=[[dog alloc] init];
[A run];//does not have a run method in the animal class, which invokes the method of the dog object.
Workaround: You can cast a to a variable of type dog*, as follows:
Dog *d= (dog *) a;//uses casts, where a and D point to the same dog object
Iii. Summary of multi-state use
(1) No inheritance, no polymorphism.
(2) The embodiment of the code: the pointer of the parent class pointer to the child class object
(3) Benefits: If the function method parameter is used in the parent class type, you can pass in the parent class and the subclass object without having to define multiple functions to match the corresponding class.
(4) Limitations: A variable of a parent class type cannot directly invoke a subclass-specific method, and must be cast to a subclass-specific method if it must be called.
Iv. String Complement content
The @ "234" string is also an object belonging to the NSString class. Here are some code descriptions for the string object:
The length method of the string object: Computes the word count of the string, rather than the number of characters, as in the Strlen function. As the result of "Ha ha123" length is 6, return unsigned long type, and the Strlen function results is 8, because a Chinese character accounted for 3 bytes.
Tip: The word count also includes spaces.
objective-c-Object-oriented polymorphic