Objective-C polymorphism -- Use of dynamic type IDs (comparison with C)

Source: Internet
Author: User

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.CodeSegment,Note: Both fraction and complex contain the print method.

 

# Import "fraction. h"
# Import "complex. h"
Int main (INT argc, char * argv [])
{
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init];
Id datavalue; // Defines an ID 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 fraction
Datavalue = F1;
[Datavalue print]; // Call the print method of Fraction
// Now datavalue gets a complex number
Datavalue = C1;
[Datavalue print]; // Call the print method of Complex

[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.