1. Construct an animal class as the parent class. The cat sub-class inherits the animal class. The Tiger sub-class inherits the cat class and each class implements a different cry method.
Excuse file 1: Animal. h
# Import <Foundation/Foundation. h>
@ Interface animal: nsobject
-(Void) cry;
@ End
Implementation file 1: Animal. m
# Import "animal. H"
@ Implementation animal
-(Void) cry
{
Nslog (@ "% @", @ "the animal is crying! ");
}
@ End
Excuse file 2: Feline. h
# Import "animal. H"
@ Interface feline: Animal
-(Void) cry;
@ End
Implementation file 2: Feline. m
# Import "feline. H"
@ Implementation feline
-(Void) cry
{
Nslog (@ "% @", @ "the feline is crying! ");
}
@ End
Excuse file 3: Tiger. h
# Import "feline. H"
@ Interface Tiger: Feline
-(Void) cry;
@ End
Implementation file 3: Tiger. m
# Import "Tiger. H"
@ Implementation Tiger
-(Void) cry
{
Nslog (@ "% @", @ "the tiger is crying! ");
}
@ 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]);
}
}
2. Construct the transportation, car, and lorry classes and define the run methods respectively.
Excuse file 1: transportation. h
# Import <Foundation/Foundation. h>
@ Interface transportation: nsobject
-(Void) run;
@ End
Implementation file 1: transportation. m
# Import "transportation. H"
@ Implementation Transportation
-(Void) Run
{
Nslog (@ "% @", @ "the transportation is runing! ");
}
@ End
Excuse file 2: car. h
# Import "transportation. H"
@ Interface car: Transportation
-(Void) run;
@ End
Implementation file 2: car. m
# Import "car. H"
@ Implementation car
-(Void) Run
{
Nslog (@ "% @", @ "the car is runing! ");
}
@ End
Excuse file 3: lorry. h
# Import "car. H"
@ Interface lorry: Car
-(Void) run;
@ End
Implementation file 3: lorry.
# Import "Lorry. H"
@ Implementation lorry
-(Void) Run
{
Nslog (@ "% @", @ "the lorry is runing! ");
}
@ End
Test File: Main. m
# Import <uikit/uikit. h>
# Import "appdelegate. H"
# Import "Lorry. H"
Int main (INT argc, char * argv []) {
@ Autoreleasepool {
Transportation * transportation = [[transportation alloc] init];
Car * car = [[Car alloc] init];
Lorry * lorry = [[lorry alloc] init];
[Transportation run];
[Car run];
[Lorry run];
Return uiapplicationmain (argc, argv, nil, nsstringfromclass ([appdelegate class]);
}
}
Oop: encapsulation, inheritance, and Polymorphism