OC object-oriented-Polymorphism
I. Basic Concepts
Polymorphism is embodied in code, that is, there are multiple forms. There must be inheritance, and there is no polymorphism without inheritance.
When polymorphism is used, dynamic detection is performed to call real object methods.
The embodiment of polymorphism in the Code is that the parent class Pointer Points to the subclass object.
Animal class declaration
Implementation of animal class
The dog class inherits from the animal class.
Dog class implementation
Test procedure:
Ii. Usage notes
Code Analysis:
Dog * D = [[animal alloc] init]; is an animal a dog? Is the semantics correct?
Nsstring * STR = [dog new]; is the dog a string? Correct?
The OC language is a language with weak syntax and will not report errors during compilation. Therefore, we must write code according to the established specifications in the actual development process, do not use a dog as a string.
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 actually inherit the automatic object class. Here, polymorphism can be used to simplify the code.
Here, you only need to write the function parameters as animal * type, so that both dog and cat objects can be passed in.
You can directly change the parameters during the call.
Limitations of polymorphism: pointer variables of the parent class cannot directly call the method unique to the subclass.
Not recommended practices ~
Animal * A = [[DOG alloc] init];
[A run]; // There is no run method in the animal class. Here, the method of the dog object is called.
Solution: You can forcibly convert a to a variable of the dog * type as follows:
Dog * D = (dog *) A; // use forced conversion. Here, A and D point to the same dog object.
Iii. Summary of Polymorphism
(1) No polymorphism without inheritance
(2) code embodiment: a pointer to a subclass object of the parent class
(3) Benefits: If the function method parameter uses the parent class type, you can pass in the parent class and subclass object, instead of defining multiple functions to match the corresponding classes.
(4) Limitations: variables of the parent class cannot directly call the method unique to the subclass. If you must call the method, you must forcibly convert it to the method unique to the subclass.
Iv. String supplements
@ "234" string is also an object and belongs to the nsstring class. The following code describes a String object:
String object length method: calculates the number of characters in a string, rather than the number of characters in a strlen function. For example, if the result of "Ha ha123" length is 6, the unsigned long type is returned, and the result of strlen function is 8, because a Chinese character occupies three bytes.
Tip: the number of words also includes spaces.
Object-oriented-Polymorphism