Objective C Polymorphism

Source: Internet
Author: User

The three basic features of object-oriented are encapsulation, inheritance, and polymorphism. Encapsulation simply combines a set of data structures and related operations defined on them into a class, inheriting a parent-child relationship, child classes can have member variables, attributes, and methods defined by the parent class.

Polymorphism means that the member variables and methods defined in the parent class inherit from the quilt class, and the parent class objects can exhibit different behaviors. All methods in OC are virtual methods. When running, the pointer type is not used. The called method is determined based on the type of the generated object.

Taking transportation as an example, the parent class is defined as vehicle. The two subclasses, bicycle and car, all inherit from this class and have the member variable name, property height, and instance method run of the parent class.

“Vehicle.h”@interface Vehicle : NSObject{    NSString *name;}@property(assign, nonatomic)int weight;-(void)run;@end<span style="font-family:SimHei;">"Bicycle.h"</span>@interface Bicycle : Vehicle@end"Car.h"@interface Car : Vehicle@end
Run methods in CAR and bicycle are implemented respectively.

@implementation Bicycle-(void)run{        [email protected]"自行车";    self.weight=100;    NSLog(@"%@ %d", name , self.weight);}@end

@implementation Car-(void)run{    [email protected]"汽车";    self.weight=2000;    NSLog(@"%@ %d", name, self.weight);}@end

Test in Main. m

#import <Foundation/Foundation.h>#import "Vehicle.h"#import "Car.h"#import "Bicycle.h"int main(int argc, const char * argv[]){    @autoreleasepool {        Car *car=[[Car alloc]init];                Bicycle *bike=[[Bicycle alloc]init];                Vehicle *veh=car;        [car run];        veh = bike;        [veh run];    }    return 0;}

Running result: Automotive 2000
Bicycle 100

Objective C Polymorphism

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.