Encapsulation, inheritance, polymorphism, classification, and Objective-C polymorphism in objective-c
Advantages of encapsulation:
Benefits of inheritance:
Notes for inheritance:
Inheritance and combination:
1 @ interface Score: NSObject 2 {3 int _ cScore; 4 int _ ocScore; 5} 6 @ end 7 8 @ implementation Score 9 @ end10 11 @ interface Student: NSObject12 {13 Score * _ socret; // The combination is used here, because it cannot be said that the Score is a student 14 int _ age; 15} 16 @ end17 18 @ implementation Student19 @ end
Combination and inheritance can be understood as follows:
- Inherited from xxx to xxx
- Combination is xxx with xxx
Polymorphism:The ability of different objects to respond to the same name method in their own way is called Polymorphism
Simply put, polymorphism is:Parent class pointer pointing to subclass object
Benefits of polymorphism:
- Receiving parameters with the parent class saves code
# Import <Foundation/Foundation. h> @ interface Animal: NSObject @ end @ implementation Animal-(void) eat {NSLog (@ "Animal ---- eat food");} @ end @ interface Dog: animal @ end @ implementation Dog-(void) eat {NSLog (@ "Dog ---- eat food") ;}@ end @ interface Cat: Animal @ end @ implementation Cat-(void) eat {NSLog (@ "Cat ---- eat food") ;}@ end // The parent class type used in the parameter, which can be passed into the subclass and parent class Object void feed (Animal *) {[a eat] ;}// this function demonstrates the benefits of polymorphism, saving the code int main () {Animal * aa = [[Animal alloc] init]; feed (aa); Dog * dd = [[Dog alloc] init]; feed (dd); Cat * cc = [[Cat alloc] init]; feed (cc );}
Limitations of polymorphism:
- Variables of the parent class cannot directly call the special method of the subclass (mandatory conversion is required)
// Forcibly convert Person * p = [[Student alloc] init]; // If learning is a Student-specific method, if you want to call the language that requires forced conversion, // OC is a weak syntax. If you use [p study], it is also possible (it is a dynamic binding), but the compiler will warn you, so do not use forced conversions to make it more reasonable. Student * s = (Student *) p; [s study];
- Dynamic binding: the dynamic calling method is determined based on the object type at runtime.
Category-Category:
Category:On the basis of not changing the original class content, you can add some methods for the class (to facilitate cooperative development)
Note: