Objective-c Inheritance and polymorphism

Source: Internet
Author: User

Learning Java We know that the class has three major characteristics, encapsulation, inheritance, polymorphism. In Objective-c, there is also the concept of inheritance, and today we will look at the inheritance and polymorphism in Objective-c.

First, let's take a look at the sample code:

Animal.h#import <Foundation/Foundation.h> @interface animal:nsobject{int food_consumption;//food intake int count;// quantity int parturition_days; Production cycle}-(int) count;-(void) SetCount: (int) c;-(int) foodconsumption;-(void) setfoodconsumption: (int) food_c;-(int) parturitiondays;-(void) setparturitiondays: (int) parturition_day; @end

Animal.m#import "Animal.h" @implementation animal-(int) count{return count;} -(void) SetCount: (int) c{count = c;} -(int) Foodconsumption{return food_consumption;} -(void) setfoodconsumption: (int) food_c{food_consumption = Food_c;} -(int) Parturitiondays{return parturition_days;} -(void) Setparturitiondays: (int) parturition_day{parturition_days = parturition_day;} @end

Panda.h#import "Animal.h" @interface panda:animal@end

Panda.m#import "Panda.h" @implementation panda@end

Tool.h#import <Foundation/Foundation.h> #import "Animal.h" #import "Panda.h" @interface tool:nsobject+ (void) Initwithanimaldictionary: (Animal *) Animal anddict: (nsdictionary *) dict; @end

Tool.m#import "Tool.h" @implementation tool+ (void) Initwithanimaldictionary: (Animal *) Animal anddict: (nsdictionary *) dict{    nsdictionary *animaldict;    if (YES = = [Animal Iskindofclass:[panda class]]) {        animaldict = [dict objectforkey:@ "Panda"];            } else{        NSLog (@ "error class!");    }    [Animal setcount:[[animaldict objectforkey:@ "Count"] intvalue];    [Animal setfoodconsumption:[[animaldict objectforkey:@ "food_consumption"] [intvalue]];    [Animal setparturitiondays:[[animaldict objectforkey:@ "parturition_days"] [intvalue]];} @end

Data.plist file

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE plist Public "-//apple//dtd plist 1.0//en" "Http://www.apple.com/DTDs/PropertyList-1.0.dtd" ><plist Version= "1.0" ><dict><key>fodder</key><dict><key>count_num</key>< String>1024</string></dict><key>panda</key><dict><key>food_consumption </key><string>2</string><key>count</key><string>6</string><key >parturition_days</key><string>76</string></dict></dict></plist>

Main.m#import <Foundation/Foundation.h> #import "Tool.h" int main (int argc, const char * argv[]) {@autoreleasepo        OL {//Insert code here ...            Panda *panda = [[Panda alloc] init];        Read plist nsstring *plistpath = [[NSBundle mainbundle] pathforresource:@ "Data" oftype:@ "plist"];            Nsmutabledictionary *data = [[Nsmutabledictionary alloc] initwithcontentsoffile:plistpath];            [Tool Initwithanimaldictionary:panda Anddict:data];        int fooder_num = 0;        int surplus = 0;            int day = 1;        Nsdictionary *fooderdict = [Data objectforkey:@ "fodder"];        Fooder_num = [[Fooderdict objectforkey:@ "Count_num"] intvalue];            Surplus = Fooder_num; while (Surplus > 0) {if (0 = = (day% [Panda parturitiondays])) {[Panda setcount: ([Panda Count]            + 1)];            } surplus = Fooder_num-([Panda Count] * [panda foodconsumption]);                Fooder_num = surplus;    if (surplus) {NSLog (@ "%d days, Panda:%d, Feed margin:%d.            \ n ", day, [Panda Count], surplus);        } day++; }} return 0;}

(i) Succession

Inheritance is an important feature of the class, and it makes it unnecessary to write repetitive code, which is very reusable. Of course, the inheritance in Objective-c is the same as in Java, not much different. Not only java,c++ also has inheritance features, but C + + supports multiple inheritance, and OBJECTIVE-C does not support multiple inheritance.

Next, we understand several concepts:

(1) Super Class (superclass), is the class you inherit, for example, Panda superclass is Animal,animal is nsobject.

(2) A parent class (ParentClass) is another way of expressing a superclass, for example, animal is the parent of Panda.

(3) Subclass (subclass), which is a class that implements inheritance, for example, Panda is a subclass of animal.

(4) A child class (ChildClass) is another way of expressing a subclass, for example, Panda is a child of animal class.

Then, talk about the working mechanism of inheritance:

(1) Method scheduling

When the code sends a message, the Objective-c method dispatcher searches the current class for the appropriate method. If the dispatcher cannot find the appropriate method in the object class that receives the message, it looks in the object's superclass.

(2) Instance variables

Let's look at how objective-c accesses instance variables. When you create a new class, its objects first inherit the instance variables from their own superclass, and optionally add their own instance variables.

Finally, when it comes to rewriting methods and making your own new subclasses, you often need to add your own methods. Sometimes, in order to introduce a unique attribute in a class, you need to add a new method. There are also times when you might need to replace or enhance an existing method defined by a superclass of this new class. When you encounter our subclass-specific methods, You only need to override the method in the subclass.

(b) polymorphic

In Objective-c, polymorphism means that a parent pointer can point to a subclass.

+ (void) Initwithanimaldictionary: (Animal *) Animal anddict: (nsdictionary *) dict;

The class method that gets the data from the dictionary in the code above is a good use of polymorphism. This method mainly reads the data from the dictionary, the example only panda a subclass, if later has more classes, then this function method needs to write a method for each subclass, but uses the polymorphic characteristic, You can reduce the problem of code redundancy by simply processing the incoming parameters separately.

Above, is the understanding of inheritance and polymorphism when learning objective-c.

Objective-c Inheritance and polymorphism

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.