Basic concepts
Program of the world and the Human "object" of the world in the mind is no difference, rich two generations inherit the parents, naturally have all the resources parents have, the subclass inherits the parent class also has the parent class all methods and attributes (member variables).
For example, the animal and the dog classes mentioned in the previous article (Objective-c of the three major features of the object):
#import<Foundation/Foundation.h>@interfaceAnimal:nsobject-(void) eat;@end@implementationAnimal-(void) eat{NSLog (@"Animal eating ...");}@end@interfaceDog:animal@end@implementationDog-(void) eat{NSLog (@"Dog eating ...");}@end
Where the dog class is inherited from the animal class.
- The dog class is a subclass of the animal class.
- The animal class is the parent class of the dog class
Advantages and Disadvantages
Advantages:
- Duplicate code extracted
- Establish a connection between classes and classes
Disadvantages:
Features in OC:
- Single inheritance, that is, each class has only one direct parent class
- All have a common parent class nsobject (because NSObject implements a lot of the underlying functionality, and if it does not inherit from NSObject, the class cannot create an instance)
Use note
- The compiler executes from top to bottom, so there should be at least a declaration of the parent class before the subclass
- A member variable name with the same name is not allowed in OC and the parent class
- A subclass in OC can have a method with the same name as the parent class, and in the case of a subclass call, take precedence over the internal search, if not one layer at a time.
- Overriding is a subclass that implements a method in the parent class, overwriting the previous implementation of the parent class
: There are three classes, the person class inherits from the NSObject class, and the student class inherits the person class.
Student *s=[[student alloc] init];
The student class and the parent class of this class are loaded into memory at this point.
Tips:
- There is a super class pointer in each class that points to its parent class
- Object has an Isa pointer that points to the class that called the object
Inheritance and Composition
Applicable occasions:
- Inheritance: When two classes have the same properties and methods, you can extract the same properties and methods into a parent class
- Combination: When Class A fully owns some of the properties and methods in class B, consider letting Class B inherit Class A (consider), in which case you might consider using a combination
Form:
- Inheritance:# # #是xxx, such as dogs are animals, can let dogs inherit animal class
- combination:# # #拥有xxx, if the student has a book, you can make the book this class as a property of the student class
[Dark Horse programmer] Objective-c inheritance of three major features of object-oriented