Inheritance and Polymorphism in Objective-C

Source: Internet
Author: User

Inheritance and Polymorphism in Objective-C
The reason why Object-Oriented Programming becomes the mainstream is inseparable from its inheritance and polymorphism. As long as object-oriented languages Support inheritance and polymorphism, of course, different OOP languages have their own characteristics. Similar to Java in OC, multi-inheritance is not supported, but C ++ in OOP supports multi-inheritance. Why does OC not support multi-inheritance will be mentioned later. When it comes to inheritance, I think of a book that describes inheritance by referencing a sentence in westward journey. "People are fucking born, and the demon is fucking born !", Presumably, Tang sanzang has also learned OOP programming. Maybe the four of them are going to go to the West to get an introduction to algorithms. Let's talk about OOP programming, data structures, and other such books. Both humans and demons belong to animals, but each has its own characteristics. Each has its own differences. Animals are parent classes, while humans and demons are sub-classes. The purpose of inheritance is to reduce code redundancy or the DRY principle (don't repeat yourself ). In Objective-C, super is a pointer to the direct parent class, while self is a pointer to itself. self is equivalent to the this pointer in java. When writing a class in OC, you can define in @ implementation which methods do not have corresponding declarations in @ interface, but this method is private and only used in class implementation. In Objectiv-C, almost all classes are inherited from the NSObject class, and there are a lot of powerful methods in the NSObject class. The following describes the methods in the NSObject class: 1. + (void) load: This method is called when the class is loaded to the runtime environment. For testing, rewrite the load method in the subclass. After the load method is overwritten, in the mian method, no object needs to be instantiated. When the class is loaded, load will not be called. load is a class method, which can be called directly by the class // rewrite the load method + (void) load {NSLog (@ "ObjectTest the load method is called !! ");} Running result: 08:58:31. 704 HelloOC [550: 303] The load method in ObjectTest is called !! 2. + (void) initialize; this method is called when the class is used for the first time. The test is not called for the second time: override the initalize method // override the initialize method, the + (void) initialize {NSLog (@ "initialize method is called when the class is used for the first time (the class is instantiated for the first time )! ");} Running result: 09:27:53. 767 HelloOC [624: 303] load method called !! 09:27:53. 769 HelloOC [624: 303] The initialize method was called (the class was first instantiated )! 3. + (id) alloc: returns an allocated memory object.-(id) init: initializes instances with allocated memory. new calls both alloc and init demo: object * object = [[Object alloc] init]; you can rewrite alloc In the subclass, and then observe the running status. // rewrite the alloc method + (id) alloc {NSLog (@ "alloc function called"); return [super alloc]; // rewrite init-(id) init {NSLog (@ "init called"); self = [super init]; return self;} Test method: one class is instantiated using alloc and init, And the other class is instantiated using new: // use ObjectTest class ObjectTest * o1 = [[ObjectTest alloc] init] for the first time; // Use ObjectTest class ObjectTest * o2 = [ObjectTest new]; running result: 09:59:58. 991 HelloOC [689: 303] load method called !! 09:59:58. 993 HelloOC [689: 303] The initialize method was called (the class was first instantiated )! 09:59:58. 993 HelloOC [689: 303] alloc function called 09:59:58. 993 HelloOC [689: 303] init was called 09:59:58. 994 HelloOC [689: 303] alloc function called 09:59:58. 994 HelloOC [689: 303] init is called 4. -(void) dealloc releases the memory occupied by the object itself; 5. -(Class) class or + (Class) class returns the Class of the current object;-(Class) superclass or + (Class) superclass returns the parent class of the current class // returns the NSString * className = (NSString *) [self class] of the current object; NSLog (@ "% @ class Display Method ", className); // return the parent NSString * superClassName = (NSString *) [self superclass] of the current object; NSLog (@ "% @ the parent Class of the Class is % @", className, superClassName); 6.-(BOOL) isKindOfClass: (Class) the example code of aClass to determine whether an instance belongs to a class or subclass is as follows: // use of isKindOfClass BOOL B = [o2 isKindOfClass: [ObjectTest class]; if (B = YES) {NSLog (@ "o2 is an object of the ObjectTest class");} 7. -(BOOL) isMemberOfClass :( Class) aClass; you can only judge whether an instance belongs to a Class, but not whether it belongs to a parent Class; // isMem BerOfClassBOOL result = [o2 isMemberOfClass: [NSObject class]; if (result = NO) {NSLog (@ "isMemberOfClass cannot judge whether it is an object of NSObject subclass");} 8. -(NSString *) description; return the description of an object in string format for debugging. // descriptionNSString * descript = [o2 description]; NSLog (@ "% @", descript ); output result: <ObjectTest: 0x100206650> 9. -(NSUInteger) hash; return the object's hash value; // hash usage NSUInteger hash = [o2 hash]; NSLog (@ "% p", hash); output result: 11:40:35. 68 5 HelloOC [1130: 303] 0x10020.b70 10. -(BOOL) isEqual :( id) object; compare whether two objects are the same. By default, the address is used for comparison, and the hash value must be the same // isEqual usage NSString * str1 = @ "111"; NSString * str2 = str1; if ([str2 isEqual: str1] = YES) {NSLog (@ "str2 = str1");} else {NSLog (@ "str2! = Str1 ");} inheritance in Objective-C is the relationship between is-a. For example, if a cat is an animal, the animal is the parent class, and the cat is a subclass of the animal. Subclass has the attributes and behaviors of the parent class, as well as its own attributes and behaviors. That is to say, "the parent class is more general and the Child class is more specific ". Use a rich second generation class to illustrate the inheritance of the next class. 1. first define a rich class code Description: 1. declare the access permission to the three attributes of @ protected. Add the getter and setter methods to the three attributes with @ property. 2. create a convenient initialization method and constructor for this class. define a card swiping Method for rich humans /// Richer. h // HelloOC // Created by ludashi on 14-7-29. // Copyright (c) 2014 ludashi. all rights reserved. // # import <Foundation/Foundation. h> @ interface Richer: NSObject {@ protected NSString * name; int age; NSString * gender;} // defines the name, age, and gender of the rich, and provide the getter and setter Methods @ property (copy, Nonatomic) NSString * name; @ property (assign, nonatomic) int age; @ property (copy, nonatomic) NSString * gender; // defines the convenient initialization method-(id) initWithName: (NSString *) vName AndAge: (int) vAge AndGender: (NSString *) vGender; // defines the constructor + (id) richerWithName: (NSString *) vName AndAge: (int) vAge AndGender: (NSString *) vGender; // defines the swipe method-(void) poss; @ end 2. coding instructions for rich humans: 1. use @ synthesize to implement the getter and setter methods. 2. initial convenience The initialization method. Use [super init] to initialize the direct parent class of rich humans, that is, NSObject 3. use the constructor to return the instantiated and initialized object # import "Richer. h "@ implementation Richer // implement the getter and setter Methods @ synthesize name, age, gender; // implement the convenient initialization function-(id) initWithName: (NSString *) vName AndAge: (int) vAge AndGender: (NSString *) vGender {if (self = [super init]) {self-> name = vName; self-> age = vAge; self-> gender = vGender;} return self;} // constructor + (id) richerWithName :( NSStrin G *) vName AndAge :( int) vAge AndGender :( NSString *) vGender {Richer * richer = [[Richer alloc] initWithName: vName AndAge: vAge AndGender: vGender]; return richer ;} // implement the card swiping method-(void) poss {NSLog (@ "% @ you can click it if you have money", name) ;}@ end 3. write rich second generation classes. Rich Second Generation and rich people have many similar attributes and methods. Therefore, rich second generation inherits rich humans and adds relevant attributes and methods, rewrite the method to be rewritten. Code Description: 1. add new hobby attributes for the rich second generation class 2. add a new method for the rich generation # import "Richer. h "@ interface Richer2nd: Richer // Richer2nd inherits all Richer Methods // Add new attributes for the rich generation @ property (copy, nonatomic) NSString * holobby; // convenient initialization function-(id) initWithName: (NSString *) vName AndAge: (int) vAge AndGender: (NSString *) vGender andholobby: (NSString *) vholobby; // compile the convenience constructor + (id) richer2ndWithName: (NSString *) vName AndAge: (int) vAge AndGender: (NSString *) VGender andholobby: (NSString *) vholobby; // Add the holobby method-(void) myholobby; @ end 4. implementation Code of various methods: 1. when you compile a convenient initialization method, use super to call the convenient Initialization Method of the parent class to initialize the methods of the inherited parent class. 2. use self to initialize new attributes # import "Richer2nd. h "@ implementation Richer2nd // implement the getter and setter methods of attributes @ synthesize holobby; // write convenient initialization functions and reuse the convenient Initialization Method of the parent class-(id) initWithName :( NSString *) vName AndAge :( int) vAge AndGender :( NSString *) vGender andholobby :( NSString *) vholobby {if (self = [su Per initWithName: vName AndAge: vAge AndGender: vGender]) {self-> holobby = vholobby;} return self;} // compile a convenient constructor + (id) richer2ndWithName :( NSString *) vName AndAge :( int) vAge AndGender :( NSString *) vGender andhober :( NSString *) vholobby {Richer2nd * richer = [[Richer2nd alloc] region: vName AndAge: vAge AndGender: vGender andholobby: vholobby]; return richer;} // rewrite the swipe method-(void) poss {[super poss]; NSLog (@ "I am a rich generation, my dad has money, I Click it! ");} // Add a new method-(void) myholobby {NSLog (@" I am a rich generation % @, I like % @ ", name, holobby );} @ end 5. the following is the running result of the above Code 08:38:12. 956 HelloOC [483: 303] if you have money for Bill, click it at 08:38:12 on February 30. 957 HelloOC [483: 303] BILL's son: if you have money, click it. 08:38:12. 958 HelloOC [483: 303] I am a rich generation. If my father has money, I will click it! 08:38:12. 958 HelloOC [483: 303] I'm rich generation BILL's son, I like the polymorphism in Objective-C. Simply put, it is different responses to different objects in response to the same method. In OC, dynamic type id is a method to realize polymorphism. id is a unique data type and can be converted to any data type, the rich and rich generation above can define id richer = nil; // test rich human richer = [Richer richerWithName: @ "Bill" AndAge: 40 AndGender: @ "Man"]; [richer poss]; // test the rich generation class richer = [Richer2nd richer2ndWithName: @ "BILL's son" AndAge: 16 AndGender: @ "male" andhober: @ "Drag Racing"]; [richer poss]; [richer myhober]; the output result of the above program is the same as that of the inherited part; another example of polymorphism: Animal is the parent class, sub-classes include Cat and Dog. The sub-class respectively overrides the eat method in the parent class. when instantiating an object, you can use the following method: Animal * Animal = nil; // animal = [Cat new]; [animal eat]; // animal = [Dog new]; [animal eat]; OCP principles and LSP principles in Object-Oriented Programming OCP: Open Closed Principle principles, Open to extensions, and disable LSP: Lishi replacement principles for modifications, where any base class can appear, subclass can certainly appear.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.