Packaging
#import<Foundation/Foundation.h>@interfacePerson:nsobject {//@public int_age;}- (void) Setage: (int) age;- (int) age;@end@implementation Person- (void) Setage: (int) Age {if(Age <=0) { age=1; } _age=Age ;}- (int) Age {return_age;}@endintMain () { person*p = [PersonNew]; //p->age = 10; //NSLog (@ "Age is:%i", p->age);[P setage:0]; NSLog (@"age is:%i", [P age]); return 0;}/** Pay attention to my naming conventions **///The benefits of encapsulation: High code security
Inheritance and composition
#import<Foundation/Foundation.h>@interfaceAclass:nsobject {int_age; int_height;}@end@implementationAClass@end/** Inheritance **/@interfacebclass:aclass{}@end@implementationBclass@end/** Combination **/@interfaceCclass:nsobject {aclass*_aclass;}@end@implementationCclass@endintMain () {return 0;}//access procedure for subclass methods and properties: If the subclass does not have access to the parent class's//subclasses and Parent classes cannot have the same member variable//subclasses and parent classes can have the same method (overridden by a method)/** Benefits of Inheritance **///not changing the original model based on the method of extension charging//establish a connection between classes and classes//The public code was extracted/** The downside of inheritance **///Strong Coupling/** Super keyword **///calling a method in a parent class directly [super Method name]//Super is calling the parent class's object method in the object method//super The class method of the parent class is called in the class method//Use scenario: Subclasses override the parent class's methods when they want to preserve some behavior of the parent class
Polymorphic
#import<Foundation/Foundation.h>@interfaceAnimal:nsobject- (void) eat;@end@implementationAnimal- (void) Eat {NSLog (@"animal is eating.");}@end@interfaceDog:animal@end@implementationDog- (void) Eat {NSLog (@"dog is eating.");}@endintMain () {Animal*a = [DogNew]; [A eat]; return 0;}/** Multi-state **///polymorphism only exists in child parent class inheritance relationship//child class object assigned to parent class pointer/** Multi-state Benefits **///save code by receiving parameters with parent class/** Limitations of polymorphism **///a variable of the parent class type cannot directly invoke a method that is unique to a subclass (consider casting)/** polymorphic Details **///Dynamic Binding: Determines the method of dynamic invocation at run time based on the type of object
Objective-c Package Inheritance Polymorphism