First create a project, then create an animal Class (Animal), then create a cat class and a dog class, and finally create a human to feed the animals.
Animal Inheritance NSObject
And cats and dogs inherit animal classes.
Human feeding also inherits NSObject
Animal class
//Declaration of Class#import<Cocoa/Cocoa.h>@interfaceAnimal:nsobject-(void) Jiao;-(void) eat;@end//Realization of Class#import "Animal.h"@implementationAnimal-(void) jiao{NSLog (@"called");}-(void) eat{NSLog (@"Eat");}@end
Cat class
#import "Animal.h"@interfaceCat:animal-(void) Jiao;@end#import "Cat.h"@implementationCat-(void) jiao{NSLog (@"Meow Meow");}-(void) eat{NSLog (@"The cat eats the fish");}@end
Human feeding
#import <Foundation/Foundation.h>#import"Animal.h"@ Interface weishi:nsobject-(void) Feed: (Animal *) Animal; @end #import " Weishi.h " @implementation Weishi-(void) Feed: (Animal *) animal{ [Animal eat];} @end
Finally instantiate the object in the main function
#import<Foundation/Foundation.h>#import "Animal.h"#import "Cat.h"#import "Dog.h"#import "Weishi.h"intMainintargcConst Char*argv[]) {@autoreleasepool {IDtest=[[Animal alloc]init]; [Test jiao]; Animal*test1=[[Cat alloc]init]; [Test1 Jiao]; IDTest2=[[Dog alloc]init]; [Test2 eat]; IDtest3=[[Weishi alloc]init]; [Test3 Feed:test2]; } return 0;}
Finally get the following.
Of course, this is basically the simplest.
Simple encapsulation of inherited polymorphism