OC Language Construction method
First, the construction method
(i) Call to construct method
Complete creation of an available object: Person *p=[person new];
The inner part of the new method calls two methods to accomplish 2 things, 1) Use the Alloc method to allocate storage space (return allocated objects), 2) Use the Init method to initialize the object.
The new method can be opened as follows:
1. Call the class method +alloc allocate storage space and return uninitialized objects
Person *p1=[person alloc];
2. Call object method-init to initialize, return the object itself
Person *P2=[P1 Init];
3. The above two processes are integrated into one sentence:
Person *p=[[person alloc] init];
Description: The Init method is the constructor method, the method used to initialize the object, note that this is an object method, and a minus sign begins. After the default initialization is complete, all member variables have a value of 0.
(ii) Code Examples of construction methods
Need 1, if I need to let each object create the initial value is 10, instead of 1, what should I do?
Demand 2, let students inherit human, ask students to initialize the object, the age is 10, the study number is 1, how to do?
(iii) Construction method use note
(1) A subclass has member variables that include its own member variables and member variables inherited from the parent class, and the member variables that inherit from the parent class should be initialized first when overriding the constructor method.
(2) Principle: Initialize the parent class first, and then initialize the subclass.
(3) The purpose of overriding the construction method: In order for the object method to be created, the member variable will have some fixed value.
(4) Note: #1先调用父类的构造方法 [super Init]; #2再进行子类内部成员变量的初始化.
Ii. Custom Construction methods
(i) Specification of custom construction methods
(1) must be an object method, starting with a minus sign
(2) The return value is typically an ID type
(3) method names usually start with Initwith
(ii) Code implementation of custom construction methods
Declaration of the Person class, which declares a custom construction method of two receive parameters
Implementation of the Person class
Student inherits from the person class and declares a constructor method that receives three parameters
Implementation of the Student class
Test the main program
(iii) Use of custom construction methods note
(1) Do your own thing
(2) The method of the parent class is given to the parent class's method to handle, and the subclass's method handles the subclass's own unique properties