Objective-C learning 04-polymorphism, objective-c04 Polymorphism

Source: Internet
Author: User

Objective-C learning 04-polymorphism, objective-c04 Polymorphism


Polymorphism

Concept of Polymorphism

Here is an example. in the morning, I spoke to my colleagues about thirst. result: My colleague A took my cup and gave me A cup of water. colleague B picked up a disposable paper cup on the water dispenser and gave me a cup of water. Colleague C gave me a bottle of drinks he just bought in the morning. Colleagues get the same request, but all three of them have their own solutions. This is polymorphism.

In the object-oriented programming theory,Polymer phism)When an operation acts on instances of different classes, different execution results are generated. That is, objects of different classes can receive different results when they receive the same message.

We know that OC is a dynamic language. When using polymorphism, the system performs dynamic detection to call real object methods. under the premise of an inheritance relationship, polymorphism is embodied in the Code as a parent class pointer pointing to a subclass object.

Implementation:

First, create an Animal class to inherit from NSObject.

 
 Animal.h
@ Interface Animal: NSObject
// Declare the way animals eat-(void) eat; @ end

 Animal.m
@ Implementation Animal
-(Void) eat {

NSLog (@ "animal food ");
} @ End

Create a Cat class and a Dog class to overwrite your own unique methods.

Cat class

 
Cat. h

// Cat inherits from Animal class
@interface Cat : Animal
@end
Cat.m
@ Implementation Cat

// Rewrite the unique method of the cat
-(Void) eat {
NSLog (@ "Cat eats fish ");

} @ End

Dog

Dog. h

// Dog inherits from the Animal class and has all attributes and methods of Animal.
@ Interface Dog: Animal
@ End
Dog.m
@implementation Dog

// Rewrite the unique method of the dog
-(Void) eat {
NSLog (@ "Dog eats bones ");
} @ End

Return to main to implement:

// Create animal object Animal * animal = [[Animal alloc] init]; // Implementation of polymorphism: // 1. the parent class Pointer Points to the subclass object animal = [[Cat alloc] init]; // is the method called at this time an animal eats? Or do cats eat? [Animal eat];
// 2. animal = [[Dog alloc] init]; [animal eat];

Print:

17:31:38. 975 DuoTai [1597: 251835] Cat eats fish

17:31:38. 975 DuoTai [1597: 251835] dog bones

 

Next, let's look at the two lines of code:

Dog * dog = [[Animal alloc] init]; // is an Animal a Dog? Is this logic correct ??

NSString * string = [[Dog alloc] init]; // The Dog is a string ??

 

We found that:

The OC language is a language with weak syntax. during compilation, no errors are reported. The system only sends a warning. therefore, we need to write code according to the established specifications in the actual development process.

 

Limitations of Polymorphism

The parent class pointer cannot directly call the unique method of the subclass. Although it can be called successfully, writing is not standard.

    Animal *animal2 = [[Cat alloc] init];
[animal2 eat];
// [animal2 catchMouth];

Benefits of polymorphism:

A girl generally prefers pets. Now she creates a girl class to keep her pets.

Girl. h

@ Class Animal; // In Girl. h, use @ class to introduce the Animal header file, telling the compiler that the following is a class @ interface Girl: NSObject
-(Void) feedAnimal :( Animal *) animal; @ end

Girl. m

# Import "Animal. h" // In Girl. m # import the Animal header file @ implementation Girl
-(Void) feedAnimal :( Animal *) animal {NSLog (@ "girl pets % @", animal );}
@end
 

Main. m

// Create a Girl object girl * Girl = [[Girl alloc] init]; // the ex-boyfriend gave it a cat, she needs to raise Cat * cat = [[Cat alloc] init]; // The girl object calls the method of raising animals and transfers the cat to [girl feedAnimal: Cat]; // now, my ex-boyfriend dumped her and met her new boyfriend. The new boyfriend gave her a Dog, and she also needed to raise Dog * d = [[Dog alloc] init]; // The girl object calls the animal feeding method and transmits the dog to [girl feedAnimal: d];

 // Print the result

22:02:22. 887 DuoTai [1812: 401072] pets for girls <Cat: 0x100206410>

22:02:22. 887 DuoTai [1812: 401072] pets for girls <Dog: 0x1003006c0>

 

Advantages of Polymorphism

Both cats and dogs inherit from the Animal class. here we can use polymorphism to simplify the code. We only need to write the function parameters as the Animal * type, then, the Dog and Cat objects can be passed in. You can directly change the parameters during the call.

Polymorphism is an important feature of object-oriented programming. It greatly enhances the flexibility and scalability of software.

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.