Objective-C polymorphism-use of dynamic type IDs

Source: Internet
Author: User

Reproduced in: http://www.cnblogs.com/54007/archive/2011/02/11/1951355.html

In C #, we use interfaces to implement polymorphism. For example, the interface iob defines a method F. There are two classes A and B that implement the IOB interface.

Iob item = new ();

Item. F (); // The execution is a.f ();

Item = new B ();

Item. F (); // The executed B. F ();

In objective-C, the meaning of the interface is very different from that of C #, and cannot be used in this way.

So how can we achieve similar results. This is a special type ID. See the following code snippet. Note: Both fraction and complex contain the print method.

 

# Import "fraction. H "# import" complex. h "int main (INT argc, char * argv []) {ngutoreleasepool * Pool = [[ngutoreleasepool alloc] init]; Id datavalue; // defines an ID type variable fraction * F1 = [[fraction alloc] init]; complex * C1 = [[complex alloc] init]; [F1 setto: 2 over: 5]; [C1 setreal: 10.0 andimaginary: 2.5]; // first datavalue gets a fractiondatavalue = F1; [datavalue print]; // call the print method of fraction // now datavalue gets a complex numberdatavalue = C1; [datavalue print]; // call complex's print method [C1 release]; [F1 release]; [pool drain]; return 0 ;}
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.