Objective-C learning 03-inheritance, objective-c03 inheritance

Source: Internet
Author: User

Objective-C learning 03-inheritance, objective-c03 inheritance
Outline:Basic concepts of InheritanceCustom Initialization MethodConstructor MethodOverride description

 

1. inherit Basic Concepts

The objects in the program are the same as those of "human". Gao fushuai inherits his parents and naturally owns all the resources of his parents, subclass inherits all attributes and methods of the parent class, except for the parent class.

When defining a new class, we often encounter such situations as the extension of a class or the correction of a class. if new classes can be defined based on existing classes, the definition of new classes will become very simple.

Similar to this, the method for defining new classes by extending or modifying existing classes is calledInheritance(Inheritance)In the inheritance relationship, the inherited class (the original class) becomesParent class)The new class obtained through this inheritance relationship is calledSubclass).

As mentioned above, inheritance means that the subclass can obtain all attributes and methods of the parent class. In addition, the subclass can also be a new class:

1.Add new instance variables

2.Append a new method that is unique to you.

3.Redefinition of methods in the parent class

Of course, it makes no sense to append only new instance variables in the subclass without changing the method. it can be said that the purpose of inheritance is to make the subclass do more things that the parent class cannot do (Extension Method ).The method for redefining the parent class in the subclass is called rewriting.. It can be divided into full rewriting and incomplete rewriting, which will be discussed later.

Advantages of inheritance: 1> omitting a large number of repeated code 2> establishing the relationship between classes.

The disadvantage is that the coupling between classes is too strong.

Inheritance relationships in eroc

1. In OC, once an inheritance relationship is established, the subclass can use all instance variables and methods in the parent class (except for the parent class private)

2. the inheritance in OC is a single inheritance relationship. A class can have only one parent class, but a class can have n child classes.

3. the inheritance relationship in OC must be reasonable.

4. Inheritance in OC is a single class inheritance. The ancestor classes of all classes are NSObject, and NSObject is the base class or root class of all classes.

5. A inherits from B. It can be said that A is A subclass of B, or that Class A is derived from Class B. Category

6.Benefits of using inheritance: If some classes are defined and many instance variables or methods are repeated (common features ), in this case, we can abstract these instance variables or methods into a new class as the parent class of these classes, so that when we define a class, directly inheriting the defined class from this parent class saves a lot of repetitive code. You only need to add your own unique features and methods to the subclass.

7. the instance variables modified by @ public and @ protected in the parent class can be accessed directly in the subclass, but the instance variable subclass modified by @ provate (private) cannot be accessed directly, access through methods only

8. when a subclass calls a method, it first finds it in its own class. If it finds it, it calls it directly. If it cannot find it, it finds it in the parent class. If it finds it, it calls it. If it cannot find it, it looks up directly, until NSObject is finally found. If the implementation is called, Crash is triggered if the implementation is not implemented.

9. Override the method of the parent class. One is to completely rewrite the method. If not completely rewrite the method, you need to use super in the method to call the implementation of the parent class to the method.

 

Notes when using inheritance

Code Demonstration:
First, create a Car class to inherit from the NSObject class.

Car. h

@ Interface Car: NSObject // Car features {@ public NSString * _ color; // color
@ Protected NSString * _ brand; // brand
@ Private NSInteger _ wheel; // wheel} // vehicle behavior-(void) run;-(void) carShock;
// Setter getter method of the instance variable-(void) setColor :( NSString *) color;-(void) setBrand :( NSString *) brand; -(NSString *) brand;-(void) setWheel :( NSInteger) wheel;-(NSInteger) wheel; @ end

Car. m

@ Implementation Car-(void) run {NSLog (@ "");}-(void) carShock {NSLog (@ ", ");}-(void) setColor :( NSString *) color {_ color = color ;}
-(NSString *) color {return _ color;}-(void) setBrand :( NSString *) brand {_ brand = brand;}-(NSString *) brand {return _ brand;}-(void) setWheel :( NSInteger) wheel {_ wheel = wheel;}-(NSInteger) wheel {return _ wheel;} @ end

The above defines a Car class, so that it has the color, brand, the attributes of the wheel, with two kinds of behavior (method): Running and Car shock ). now, we want to add a property of the maximum carrying capacity to the Truck and a method for outputting its own information, and include the attributes and methods of the Car, so we need to use inheritance;

In this case, we only need to create a new class that inherits from the Car class and write its own unique methods and attributes in the new class.

Create a Truck class inherited from Car:

Truck. h

@ Interface Truck: Car {// NSString * _ color; the instance variable CGFloat _ maxLoad with the same name as the parent class cannot be defined in the error subclass; // maximum load}-(void) setMaxLoad :( CGFloat) manLoad;-(CGFloat) maxLoad; // Method for describing truck information-(void) describeTruck;-(void) run; // The subclass can define a method with the same name as the parent class. This form is called method rewriting //. Why do we need to rewrite the method? Because the methods provided by the parent class cannot meet the requirements of the subclass // There are two methods to override the parent class. One is to completely override the parent class, another method is incomplete rewriting.

@ End

Truck. m

@ Implementation Truck // _ setter getter method of maxLoad-(void) setMaxLoad :( CGFloat) manLoad {_ maxLoad = manLoad;}-(CGFloat) maxLoad {return _ maxLoad ;} // Method for describing the truck information-(void) describeTruck {NSLog (@ "% @ % ld %. 2f ", _ color, _ brand, self. wheel, _ maxLoad) ;}// Note: Since _ wheel is private, it cannot be accessed directly in the subclass, self // needs to be used to override the run method of the parent class. // if the method implementation of the parent class is not called when the parent class method is rewritten, it is called a full override-(void) run NSLog (@ "the truck is running");} // Method for rewriting the car shock-(void) carShock {
// Super compiler instruction, used to call the method of the parent class. It is suitable for [super carShock]; NSLog (@ "") to retain some methods of the parent class ");} @ end

Return to main.

// Create a large Truck object Truck * truc = [[Truck alloc] init];
// Color brand wheel is a truc inherited from the parent class. color = @ "blue"; // color truc. brand = @ "Dongfeng"; // brand truc. wheel = 12; // wheel // maxLoad is the truc unique to the subclass. maxLoad = 120.0; // load // call the parent class method // [truc carShock]; [truc run]; // call the method used to describe the truck [truc describeTruck];
// Call che Zhen's method [truc carShock];

Print result:

22:46:44. 741 OCLessonInherit-03 [1759: 364404]Trucks running

22:46:44. 742 OCLessonInherit-03 [1759: 364404]BlueDongfeng12 120.00

22:46:44. 742 OCLessonInherit-03 [1759: 364404]No earthquake,I don't know what it feels like

22:46:44. 742 OCLessonInherit-03 [1759: 364404]Poor trucks

3. Initialization Method

-(Id) init {// execute the init method self = [super init] in the parent class
If (self) {// initialization settings _ taxiMeter = @ "Price calculator" ;}// return the object after initialization return self ;}

Initialization Process:

During initialization, first call the [super init] Method of the parent class (recursively returning it to the initialization method in the NSObject class), use self to receive the result, and then judge whether it is nil based on the value in self, determine whether to initialize your own instance variables. If it is nil, it means that the initialization method of the parent class has failed and it will not initialize its own instance variables. If it is not nil, it indicates that the parent class initialization method is successful, and then the instance variables are initialized.

2. Custom Initialization Method

Naming rules:

1. It must be an object method, starting with minus sign-

2. the return value type is id (preferably id) or the current class type.

3. It must start with initWith

4. There are two methods for custom initialization: full custom initialization and incomplete initialization.

Example:

Incomplete initialization method:

// Only initialize the name and age-(id) initWithName :( NSString *) name age :( NSInteger) age {if (self = [super init]) {_ name = name; _ age = age;} return self ;}

Fully custom initialization:

// Initialize all instance variables

- (id)initWithName:(NSString *)name age:(NSInteger)age height:(CGFloat)height {
if (self = [super init]) {
     _name = name; _age = age; _height = height; } return self;}

3. constructor Method

Naming rules

1. The traversal constructor method must be a class method, starting with a plus sign (+)

2. the return value type must be id.

3. Start With a lower-case class name + With + instance variable name With the underline removed and the first letter is capitalized

Note:

4. the constructor is also called the factory method, which is used to quickly and quickly create objects.

5. essence of the constructor method: Inside the method, a created object is taken as the return value of the method.

6. the constructor method must be used together with the custom initialization method.

 

Example (corresponding to the two custom initialization methods listed above ):

+ (Id) personWithName :( NSString *) name age :( NSInteger) age {
// Use a created object as the return value of the constructor method. return [Person alloc] initWithName: name age: age];}
+ (Id) personWithName :( NSString *) name age :( NSInteger) age hight :( CGFloat) hight {
Return [[Person alloc] initWithName: name age: age height: hight] ;}@ end

Main

Person * p = [[Person alloc] init]; NSLog (@ "% @-% ld-%. 2f", p. name, p. age, p. height );

// Call the custom initialization method Person * p1 = [[Person alloc] initWithName: @ "Wu xie"]; NSLog (@ "% @-% ld-%. 2f ", p1.name, p1.age, p1.height); Person * p2 = [[Person alloc] initWithName: @" Hua qigu "age: 18]; NSLog (@ "% @-% ld-%. 2f ", p2.name, p2.age, p2.height );
  
// Call the full initialization method Person * p3 = [[Person alloc] initWithName: @ "White sub-painting" age: 22 height: 70]; NSLog (@ "% @-% ld-%. 2f ", p3.name, p3.age, p3.height); // call the convenience constructor method Person * p4 = [Person personWithName: @" "]; NSLog (@ "% @-% ld-%. 2f ", p4.name, p4.age, p4.height); Person * p5 = [Person personWithName: @" "age: 15]; p5.name = @" "; p5.height = 0.3; NSLog (@ "% @-% ld-%. 2f ", p5.name, p5.age, p5.height); Person * p6 = [Person personWithName: @" "age: 26 hight: 1.65]; NSLog (@ "% @-% ld-%. 2f ", p6.name, p6.age, p6.height );

The complete code is as follows:

Person. h

# Import "Car. h "@ interface Person: Car {NSString * _ name; NSInteger _ age; CGFloat _ height;}-(void) setName :( NSString *) name;-(NSString *) name; -(void) setAge :( NSInteger) age;-(NSInteger) age;
-(Void) setHeight :( CGFloat) height;-(CGFloat) height; // custom initialization method-(id) initWithName :( NSString *) name;-(id) initWithName :( NSString *) name age :( NSInteger) age;-(id) initWithName :( NSString *) name age :( NSInteger) age height :( CGFloat) height; // write a class method of the traversal constructor + (id) personWithName :( NSString *) name; + (id) personWithName :( NSString *) name age :( NSInteger) age; + (id) personWithName :( NSString *) name age :( NSInteger) age hight :( CGFloat) hight; @ end
# Import "Person. h" @ implementation Person-(void) setName :( NSString *) name {_ name = name ;}
-(NSString *) name {return _ name;}-(void) setAge :( NSInteger) age {_ age = age;}-(NSInteger) age {return _ age ;} -(void) setHeight :( CGFloat) height {_ height = height;}-(CGFloat) height {return _ height ;} // customize the initialization method // whatever the initialization method, you must first determine whether the parent class has been initialized successfully-(id) initWithName :( NSString *) name {if (self = [super init]) {_ name = name;} return self;}-(id) initWithName :( NSString *) name age :( NSInteger) age {if (self = [super init]) {_ name = name; _ age = age;} return self;}-(id) initWithName :( NSString *) name age :( NSInteger) age height :( CGFloat) height {if (self = [super init]) {
_ Name = name; _ age = age; _ height = height;} return self ;}
+ (Id) personWithName :( NSString *) name {
// The essence of the constructor is to create an object in the constructor method, then return this object as the return value // The traversal constructor method must be used with the custom Initialization Method Using Person * p = [[Person alloc] initWithName: name]; return p ;} + (id) personWithName :( NSString *) name age :( NSInteger) age {// return [[Person alloc] initWithName: name age: age] ;}+ (id) personWithName :( NSString *) name age :( NSInteger) age hight :( CGFloat) hight {
Return [[Person alloc] initWithName: name age: age height: hight] ;}@ end

 

Related Article

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.