Inheritance (v)

Source: Internet
Author: User

Inherited

Inheritance, is one of the three characteristics of object-oriented, the emergence of inheritance is to reduce a lot of redundant code, because it is in each class, the same characteristics and behavior is collected into another class, and then these classes inherit from the centralized class, you can put all the characteristics and behavior of this centralized class to inherit. Then use.

When it comes to classes, you should refer to the subclass and the parent class, both of which exist at the same time, not that I am a parent, or that I am a subclass, and that they are interdependent. Who is the parent of the class, who is the subclass.

Subclasses inherit the parent class, which is unidirectional and cannot inherit from each other.

Inheritance also has transitivity, in the vernacular, that is: Class B if it inherits from Class A, Class C inherits from Class B, when Class B is a subclass of Class A, Class C is a subclass of Class B, A is the parent of B, and B is the parent class of C. In this case, B (subclass) can inherit all instance variables and methods of a (parent class), this is all instance variables and methods, but also the private modified instance variables, but the private decoration of the instance variable, inherited it cannot be used directly. C (subclass) Inherits all instance variables and methods of B (parent class), including instance variables of private adornments.

In OC, the final parent class of all classes is NSObject (this class has no parent class, called the Root Class).

Subclasses inherit from the parent class method, which can be overridden. Note here that 1, overriding the parent class method, does not need to be declared, it does not need to be declared in the. h file. 2. Overriding the parent class method must be the same as the parent class method name.

An exercise:

Animal.h: Inheriting from NSObject

#import <Foundation/Foundation.h>

@interface animal:nsobject{

NSString *_kind;

NSString *_color;

@private

NSString *_name;

}

-(void) sayhi;

-(NSString *) kind;

-(NSString *) color;

-(void) Setkind:(nsstring *) kind;

-(void) SetColor:(nsstring *) color;

@end

animal.m

#import "Animal.h"

@implementation Animal

-(void) sayhi{

NSLog (@ "Animals barking ...");

}

-(NSString *) kind{

return _kind;

}

-(NSString *) color{

return _color;

}

-(void) Setkind:(NSString *) kind{

_kind = kind;

}

-(void) SetColor:(NSString *) color{

_color = color;

}

@end

Cat.h: Inheriting from the Animal class

When inheriting, use #import to introduce the parent class header file

#import "Animal.h"

@interface cat:animal{

-(void) test;

@end

Cat.m

#import "Cat.h"

@implementation Cat

-(void) test{

_kind = @ "";

_color = @ "";

_name = @ "";

}

Overrides the method inherited by the parent class.

1. No declaration

2. The method name must be the same as the parent class

-(void) sayhi{

NSLog (@ "Meow");

}

@end

SmallCat.h: Inheriting from Cat class

#import "Cat.h"

@interface Smallcat:cat

@end

Smallcat.m

#import "SmallCat.h"

@implementation Smallcat

@end

Main.m

#import <Foundation/Foundation.h>

#import "Cat.h"

#import "SmallCat.h"

int main (int argc, const char * argv[])

{

@autoreleasepool {

Cat *c = [[Cat alloc]init];

[C sayhi];//2015-04-15 10:47:46.528 oclesson3_ inheritance [951:41,625] animal barking ...

[C setkind:@ "Husky ..."];

[C setcolor:@ "White:"];

NSLog (@ "%@", c.kind);//2015-04-15 10:54:16.185 oclesson3_ inheritance [1045:44,417] Husky.

NSLog (@ "%@", C.color);//2015-04-15 10:54:16.186 oclesson3_ inheritance [1045:44,417] white.

C.kind = @ "Blue cat.";

C.color = @ "White ...";

NSLog (@ "%@", c.kind);//2015-04-15 10:54:16.186 oclesson3_ inheritance [1045:44,417] Blue Cat.

NSLog (@ "%@", C.color);//2015-04-15 10:54:16.186 oclesson3_ inheritance [1045:44,417] white ...

[C Sayhi];

Smallcat *SC = [[Smallcat alloc] init];

[SC Sayhi];

}

return 0;

}

Self

Self is a pointer to their own (can be printed out to see the address), generally used in the class, to call their own method, of course, it must be understood here, self if in the instance method, can only adjust the instance method, in the class method can only tune the class method, not allowed in the instance method of the class method, the method of tuning the

The self-tune itself is in the form of: [The method name of this class].

Super

Super's appearance is because in the subclass, self to rewrite the parent class's method, the implementation of this class is the overridden method (if the method is not called in this class, the system will automatically go to the parent class, if the parent does not have this method, will go to the parent class to find the parent class, always find the NSObject root class, If not, then the program crashes), if you want to execute the method of the parent class, then use Super to invoke the parent class method.

Self is a pointer, super is not a pointer, nor is it a variable, and super is the compiler's instruction. A method that is specifically used to access the parent class. If super is used in this class (assigning it as a variable or as a pointer to a print address), it will hold an error called "Undefined Super".

Super and self, in the instance variable can only invoke the instance method, in the class method can only invoke the class method, not allowed in the instance method of the class method, in the class method to tune the instance method.

An example:

Person.h: Inheriting NSObject

#import <Foundation/Foundation.h>

@interface Person:nsobject

-(void) sayhi;

-(void) test;

+ (void) test2;

+ (void) test3;

@end

Person.m

#import "Person.h"

@implementation person

-(void) sayhi{

NSLog (@ "Eat it?" ");

}

Test self

-(void) test{

Self is a pointer to yourself.

Self: Calls its own method within the class.

Self can invoke instance methods in an instance method,

NSLog (@ "%p", self);//2015-04-15 14:50:24.972 oclesson3_self_super[1733:91671] 0x100114040

[Self sayhi];

Self in an instance method, the class method cannot be called.

[Self test2];

}

+ (void) test2{

Self can call a class method in a class method.

[Self test3];

Self in a class method, you cannot invoke an instance method.

[Self test];

}

+ (void) test3{

}

@end

Student.h: Inherit from person

#import "Person.h"

@interface Student:person

-(void) stutest;

+ (void) stuTest1;

@end

Student.m

#import "Student.h"

@implementation Student

-(void) sayhi{

NSLog (@ "about? ");

}

Test Super

-(void) stutest{

Super can call methods of the parent class.

Super is a compiler directive (not a variable, not a pointer) that is used to access the parent class method.

NSLog (@ "%p", super);//Error Super undefined

[Super Sayhi];

The example method can be adjusted in the Super test];//instance method.

[Super test2];//instance method cannot tune the class method.

}

+ (void) stutest1{

[Super Test2];

[Super Test3];//super calls a class method in a class method

[Super Test];//super cannot invoke an instance method in a class method.

}

@end

Main.m

#import <Foundation/Foundation.h>

#import "Person.h"

#import "Student.h"

int main (int argc, const char * argv[])

{

@autoreleasepool {

Person *P1 = [[Person alloc] init];

NSLog (@ "%p", p1);//2015-04-15 14:50:24.972 oclesson3_self_super[1733:91671] 0x100114040

[P1 Sayhi];

[P1 test];//2015-04-15 14:49:07.067 oclesson3_self_super[1710:90956] did you eat?

Student *stu = [[Student alloc] init];

[Stu Sayhi];//2015-04-15 15:04:35.318 oclesson3_self_super[1798:96571] about?

[Stu Stutest];//2015-04-15 15:05:43.319 oclesson3_self_super[1811:97083] did you eat?

}

return 0;

}

The complete initialization method:

The complete initialization method, to add a judgment, is to follow a sequence, first initializes the parent class, if the parent class is initialized successfully, returns an address to the subclass, the subclass receives the address, and then initializes itself. If the parent class initializes, and fails, it returns a null value to the subclass, and when the subclass receives the null value, it does not execute its own initialization method, but returns the null value to the program to stop.

The above implementation procedure Code is as follows:

Person.h inherited from NSObject

#import <Foundation/Foundation.h>

@interface person:nsobject{

NSString *_name;

Nsinteger _age;

}

-(Instancetype) Initwithname:(NSString *) name Age: (Nsinteger) age;

@end

Person.m

#import "Person.h"

@implementation person

-(instancetype) Initwithname:(NSString *) name Age: (Nsinteger) age{

    //Initialize something inherited from the parent class.

   //1. Initialization failed with a return value of nil (empty)

   //2. The address is changed after initialization, (Nsmutablearray) class cluster

    self = [super init];

   //once something inherited from the parent class fails to initialize, do not assign a value to your instance variable.

    if (self) {

        _ name = name;

        _age = age;

   }

   //If initialization fails, returns nil

   //If initialization succeeds return address.

     return to self;

@end

//Specify initialization method (find after Class)

Here, we first call the Init initialization method of the parent class (NSObject) with super, and then use the self pointer to receive the address returned by [Super Init]. If the initialization of the parent class fails, returns an empty to self, when judging the value of the itself, if not NULL, initializes the class for itself, otherwise returns empty.

It is worth noting that [super Init] refers to the initialization method that super calls the parent class, not necessarily init, or initxxx. (This condition occurs only if a subclass inherits it after inheritance).

An example:

Student.h Inherit from person

Declares an initialization method that, when implementing the initialization method, first receives the result of the initialization of the [Super Initxxx] parent class with self, and if successful, resumes the initialization itself after the return address.

#import "Person.h"

@interface student:person{

NSString *_num;

}

-(Instancetype) Initwithname: (NSString *) name Age: (nsinteger) Age num: (NSString *) num;

@end

Student.m

#import "Student.h"

@implementation Student

-(Instancetype) Initname: (NSString *) name Age: (nsinteger) Age num: (NSString *) num{

self = [super Initname:name age:age];

if (self) {

_num = num;

}

return self;

}

@end

self = [super Initname:name age:age]; This means that super tuned the initialization method of the parent class (person), and if successful, it receives the address, then proceeds to execute _num = num;

The same:

CollageStudent.h inherited from Student

#import "Student.h"

@interface collagestudent:student{

NSString *_major;

}

-(Instancetype) Initname: (NSString *) name Age: (nsinteger) Age num: (NSString *) num Major: (NSString *) major;

@end

Collagestudent.m

#import "CollageStudent.h"

@implementation Collagestudent

-(Instancetype) Initname: (NSString *) name Age: (nsinteger) Age num: (NSString *) num Major: (NSString *) major{

self = [super Initname:name age:age Num:num];

if (self) {

_major = major;

}

return self;

}

@end

Is the same way of execution, step by step, starting from the highest parent class, the subclass self is received and judged before initializing itself.

Convenience Builder:

The convenience constructor is a class method designed to make it easier for users to use, but it can be a little cumbersome when writing convenience constructors.

Note that the following are:

1, to facilitate the appearance of the constructor, must be with the corresponding initialization method appear together;

2, the method name starts with the class name (the class name must all lowercase), followed by the initialization method Init all the things behind. For example: The initialization method is:

-(Instancetype) Initname:(NSString *) name:(Nsinteger) age;

The Convenience Builder is: (Person Class)

+ (instancetype) PersonName:(NSString *) name Age:(Nsinteger) age;

The convenience of the implementation of the constructor is to put alloc this memory allocation of the steps in the constructor, in MAIN.M and so on the use of convenient constructors, do not need to alloc.

Example:

Person.h

#import <Foundation/Foundation.h>

@interface person:nsobject{

NSString *_name;

Nsinteger _age;

}

-(Instancetype) Initname:(NSString *) name:(Nsinteger) age;

Convenience constructors (class method)

The precondition of writing convenience constructor is to have a corresponding initialization method

The method name begins with the class name, the class name is lowercase, followed by everything behind Init.

+ (instancetype) PersonName:(NSString *) name Age:(Nsinteger) age;

@end

Person.m

#impor T "Person.h"

-(instancetype) Initname:(NSString *) Name Age:(Nsinteger) age{

    self = [super init];

    if (self) {

        _name = name;

        _age = age;

   }

    return to self;

//convenience builder implementation

+ (instancetype) PersonName:(NSString *) name age :(Nsinteger) age{

&NBSP;&NBSP;&NBSP;

    person *p = [[Person Alloc]initwithname:name Age:age];

    return p;

@end

Person *p = [[Person alloc]initname:name age:age], which means to move the steps that should be alloc in main to the. m implementation file.

Main.m

#import <Foundation/Foundation.h>

#import "Person.h"

int main (int argc, const char * argv[])

{

@autoreleasepool {

Person *p = [[Person alloc]initname:@ "small black" age:18];

Person *P2 = [Person personname:@ "small white" age:18];

}

return 0;

}

Person *p = [[Person alloc]initname:@ "small black" age:18]; This statement is a direct invocation of the initialization method, requires alloc;

Person *P2 = [Person personname:@ "small white" age:18]; This statement is called a convenience constructor and does not require alloc. It is much more convenient than alloc.

Inheritance (v)

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.