Oop: encapsulation, inheritance, polymorphism (continued)

Source: Internet
Author: User

Excuse file 1: Bird. h

# Import <Foundation/Foundation. h>

@ Interface bird: nsobject
{
@ Private
Int _ weight;
Nsstring * _ name;
}
-(Void) fly;

@ End


Implementation file 1: Bird. m

# Import "bird. H"

@ Implementation bird
-(Void) fly
{
Nslog (@ "% @", @ "bird is flying! ");
}
@ End

 

Excuse file 2: Sparrow. h

# Import "bird. H"

@ Interface Sparrow: Bird
{
// @ Protected
// @ Public
// @ Private
Nsstring * _ id;
}
@ Property (nonatomic, assign) nsstring * ID;
-(Void) set_id :( nsstring *) ID;
-(Void) print_id;
-(Void) Sing;
@ End


Implementation file 2: Sparrow. m

# Import "Sparrow. H"

@ Implementation sparrow
-(Void) set_id :( nsstring *) ID
{
_ Id = ID;
}
-(Void) print_id
{
Nslog (@ "% @", _ id );
}
-(Void) Sing
{
Nslog (@ "% @", @ "Sparrow is singing! ");
}

@ End


 

Excuse file 3: blacksparrow. h

# Import "Sparrow. H"

@ Interface blacksparrow: sparrow
-(Void) Eat;
-(Void) Sing;
@ End

Implementation file 3: blacksparrow. m

# Import "blacksparrow. H"

@ Implementation blacksparrow
-(Void) fly
{
Nslog (@ "% s" ,__ pretty_function __);
}
-(Void) Eat
{
Nslog (@ "% s" ,__ pretty_function __);
}
-(Void) Sing
{
Nslog (@ "% s" ,__ pretty_function __);
}
@ End

Test File: Main. m

Int main (INT argc, char * argv []) {
@ Autoreleasepool {
Bird * bird = [[Bird alloc] init];
[Bird fly];
Sparrow * sparrow = [[Sparrow alloc] init];
[Sparrow fly];
[Sparrow sing];
[Sparrow set_id: @ "1234"];
[Sparrow print_id];
Bird * bird1 = [[blacksparrow alloc] init];
Blacksparrow * BS = bird1; // forced type conversion
BS. ID = @ "sssss ";

[Bird1 Fly];
[Bird1 eat];
[Bird1 sing];
[Bird1 print_id];
Return uiapplicationmain (argc, argv, nil, nsstringfromclass ([appdelegate class]);
}
}


Oop: encapsulation, inheritance, polymorphism (continued)

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.