OC language-inheritance, dot syntax, category

Source: Internet
Author: User
Tags instance method

1 inheritance

1.0 Object-oriented three basic features: 1. Encapsulation 2. Inheritance 3. Polymorphism

1.1 Inheritance in life

-"The Life Logic of Inheritance"

A. Inheritance: Pre-grant, no need to build yourself

B. Human father class

Men and women sub-categories

Jobs and Zhang Ziyi's object

- The concept of inheritance: Inheritance (also known as derivation).

The parent class has properties and methods that the subclass directly obtains, and this process is called inheritance.

Subclasses, on the basis of the parent class, derive their own unique properties and methods, called derivations.

-"Parent-child category of various titles:

Parent class ParentClass Super class Supperclass base class BaseClass

Subclass ChildClass Subclass Subclass Derived class DerivedClass

1.2 Inheritance in code

-"Basic syntax for inheritance"

A. Grammatical form

@interface Child class Name: Parent class name

@interface person:nsobject// Any class in OC must inherit a class, that is, each must inherit one

@end

B. After inheritance

Subclasses can use all methods of the parent class

Subclasses can get a non-private member variable of the parent class

C. class field and member method access control

                @interface Person:nsobject//nsobject Root class {@protected//protected:,//subclass inherits the parent class,//subclasses can directly use the protected member variable of the parent class    int _age; @public// Public: In-class and out-of-class functions//Can be directly used by public member variables//This will damage the object information to some extent the hidden    int _height; @private//private: The  class-in method can directly use the private//out-of-class methods cannot be directly used ,///But can be accessed and used indirectly through an instance method,//subclass inherits the parent class,//subclasses can indirectly use the parent class's private variable int _money through the method of the parent class   ;}

Member method: No @private @protected @public such access control

The OC Neutron class inherits the parent class and then has the method of the parent class.

Note:

1. Methods in OC are similar to virtual functions in C + +

2. OC is not a private method similar to C + +,

But it can be done in other ways.

-"Inheritance in memory of the embodiment

Subclasses inherit the composition of the subclass object after the parent class:

A. Inherited member variables of the parent class

B. Subclass-specific member variables

-"Overwrite" (override override)

A. Subclasses inherit from the parent class, sometimes not suitable for subclasses, subclasses can override this method

B. Rewriting is a way to re-implement the parent class (the method name implements the content differently)

C. After the subclass overrides the parent class method, the subclass object finally executes the method after the subclass is overridden

-"polymorphic

A. In fact, polymorphism means that the same interface is different implementation//rewrite

B. From the OC message mechanism: Send the same message to different objects, react differently

-"When to use inheritance"

A. Creating a large number of similar classes

"Example" Create chess pieces, car horse elephant cannon.

You can first create a pawn class as the parent class.

B. Inherit an official class, add properties and methods, and create a new class that is more consistent with the current project.

C. Unifying interfaces with inheritance (not commonly used)

-"The role of Inheritance"

Code reuse, save resources and improve efficiency

-"Class cluster"

A. Cluster is a common design pattern in the underlying framework, based on the idea of an abstract factory pattern.

It sets a number of related private specific factory subclasses below the abstract superclass;

B. Class clusters combine some private, specific subclasses under a common, abstract superclass,

Organizing classes in this way simplifies the public schema of an object-oriented framework,

Without diminishing the richness of the function;

c.nsstring Nsarray nsdictionary nsnumber are all [ class cluster/factory class ]

Cannot be inherited, even if inherited, cannot use the parent class method.

2-point syntax and attribute keyword @property use

-"The relationship between Point Grammar and Setter/getter

Dot syntax and the use of @property keywords,

is the syntax substitution for the Setter/getter method;

Its principle, similar to the C language, is substituted in the program's compilation phase.

The substitution, for text substitution, does not check the program's logical semantics.

A. As long as a class has a Setter/getter method that meets the requirements, you can use '. ' Operation

B.xiaohong.name = @ "Xiaohong"; The setter method is actually called here

NSString *namestring = Xiaohong.name; The Getter method is actually called here.

c. The ID type cannot be used directly with point operations (requires coercion of type conversions)

-"Attribute @property

A. @property Automatic declaration of setter and Getter methods

@synthesize automatically implement setter and Getter methods

B. @property Nsuinteger x; Create the following two methods

-(void) SetX: (Nsuinteger) x;

-(Nsuinteger) x;

@synthesize x = _x; implement the following two methods Xcode4.6 can be omitted later

-(void) SetX: (Nsuinteger) x

{

_x = x;

}

-(Nsuinteger) x

{

return _x;

}

-"Property modifier

Read-only modifier

Only getter method, no setter method

@property (readonly) NSString * name;

Direct assignment modifier (default)

@property (assign) NSString * name;

Read-write modifier (default)

Create both the set method and the Get method

@property (ReadWrite) NSString * address;

Atomic manipulation modifier (default)

@property (Atomic) NSString * Group;

Non-atomic operation

@property (nonatomic) NSString * grade;

Multiple property modifiers that need to be separated by commas

@property (Nonatomic, readonly, getter = birth) NSString * BirthDay;

Alias the set method and the Get method

@property (getter = personage, setter = Setagi:) int age;

3. Categories/Categories

(1) Updating methods of existing classes, which are named

(2) Unable to add new attribute

(3) Includes all classes within the Nsstring,nsdictionary,nsarray,nsnumber can be expanded to use category

-Basic syntax for category

The declaration section of the category @interface  nsstring (Print)-(void) print;//added new method (cannot have member variable declaration) ... @end//Category implementation part @implementation NSString (Print)-(void) print{} ... @end

Note: Once the class is used to add methods to existing classes, the object of this class can use this method

-". Category features:

A. Class additions that can be made to an existing/system-native

B. Class methods can be categorized and managed,

you can spread the implementation of a class into multiple different files or multiple different frameworks.

-"Issues to be noted in the use of categories

A. You cannot add member variables in a category

B. Using the category Additions method to import the category header file

C. Methods in the parent class category, and subclasses can also use the

-"Class extension/anonymous category (class extend)

when you don't want to expose some of the class's methods, we can use the class extension

A. Basic syntax for class extensions

The declaration of the class extension is written in the. m file

@interface person ()//No Name  -(void) song; @end @implementation person-(void) song{nslog (@ "Hello");} @end

Note:

A class extension has only a declaration part and no implementation part.

The methods declared in the class extension need to be implemented in the implementation of the class

B. Features of the class extension

1. Private methods can be implemented

2. Make it easy for programmers to call a method that is not public

3. You can declare member variables

eg. sample code

Account.h file

#import <Foundation/Foundation.h> #define RATE 0.0325@interface account:nsobject{  nsuinteger _uid;//user account  nsstring* _upasswd;//user password double  _uamount;//account balance  double _uperiod;//savings Time  double _rate;//one-year deposit rate}@ Property (assign,nonatomic) Nsuinteger uid; @property (copy,nonatomic) nsstring* upasswd; @property (assign,nonatomic) Double uamount; @property (assign,nonatomic) double uperiod; @property (assign,nonatomic) Double rate;-(void) Deposit: ( Double) money;//deposit-(double) Withdraw: (double) money;//withdrawal-(double) Settlementonwithdraw: (double) settlement interest on withdrawal ( Double) settlementuponyear;//Annual settlement interest-(double) interestcaculate;//Interest Calculation-(double) incomecaculate;//maturity and principal income + (void) testbyself;//self-test method of this class-(ID) Initwithuid: (Nsuinteger) AUid andupasswd: (nsstring*) aupasswd Anduamount: (double) auamount ; @end

Account+currency.h file

#import "Account.h" @interface account (currency)-(void) Deposit: (double) money withforeigncurrency: (char) type;//deposit-( Double) Withdraw: (double) money withforeigncurrency: (char) type;//withdrawal @end

ACCOUNT.M file

#import "Account.h" #import "account+currency.h"//#include "account_dollar.h" @implementation account@synthesize uid= _uid, @synthesize Uamount=_uamount, @synthesize upasswd=_upasswd; @synthesize rate=_rate; @synthesize uperiod=_uperiod  ;-(void) Deposit: (double) money{_uamount + = money; NSLog (@ "Current account balance after deposit:%.2LF", _uamount);}  -(double) Withdraw: (double) money{_uamount + = [self settlementonwithdraw:_uamount];  _uamount-= money;  NSLog (@ "Current account balance after withdrawal:%.2LF", _uamount); return _uamount;}    -(double) Settlementonwithdraw: (double) money//settlement interest when withdrawing funds {double Retmoney = money; Return Retmoney *= (_rate * _uperiod);} -(double) settlementuponyear//annual settlement Interest {return _uamount *= (1+_rate);}    -(double) interestcaculate//maturity interest Calculation {double interest = 0.0; return interest = _uamount * _rate;}  -(double) incomecaculate//maturity principal and interest income {double income = 0.0; Return income = _uamount* (1+_rate);}    + (void) testbyself//This class of self-test method {//Create a new account instance account* Aaccount = [[Account Alloc]init];    Show account Initial status NSLog (@ "%@", Aaccount); DepositTest [Aaccount deposit:100.00];    NSLog (@ "%@", Aaccount);  The simulated date interval int n = 36;  for (int i=1;i<=n;i++) {aaccount.uperiod = (double) i/(double) 365;  }//Withdrawal test [Aaccount withdraw:50.00];    NSLog (@ "%@", Aaccount);    Simulate saving a pen before and to a one-year period [Aaccount deposit:100.00];  Analog time lapse for (int i=n;i<=365;i++) {aaccount.uperiod = (double) i/(double) 356;   } [Aaccount settlementuponyear];    NSLog (@ "%@", Aaccount);  Foreign currency deposit//Aaccount.foreign_amount = 1.0;  [Aaccount deposit:200.00 withforeigncurrency: ' $ ']; }-(ID) Initwithuid: (Nsuinteger) AUid andupasswd: (nsstring*) aupasswd Anduamount: (double) auamount{if (self = [super init    ]) {_rate = rate;    _uperiod = 1/365;    _uid = AUid;    _UPASSWD = aupasswd;  _uamount = Auamount; } return self;} -(ID) init{return [self initwithuid:1 andupasswd:@ "123456" anduamount:1.0];}    -(NSString *) description{nsstring* passwd_des = @ "******"; return [nsstring stringwithformat:@ user account:%06lu user password:%@ account balance:%.2LF (RMB) Current term deposit rate (one year):%.4LF storage Time:%.2LF (year) ", _Uid,passwd_des,_uamount,_rate,_uperiod];} @end

ACCOUNT+CURRENCY.M file

#import "Account+currency.h" #import "Account_dollar.h" @implementation account (currency)  //Foreign currency deposit Method-(void) Deposit: (Double) money withforeigncurrency: (char) type//deposit {  double fa = self.foreign_amount;  FA + + money;  Self.foreign_amount = FA;  NSLog (@ "Current foreign currency (%c) account balance after deposit:%.2LF", Type,self.foreign_amount);}  Foreign currency withdrawal method has a bug, please modify the correct self!!! -(double) Withdraw: (double) money withforeigncurrency: (char) type//withdrawal {  Self.foreign_amount + = [self SettlementOnWithdraw:self.foreign_amount];  Self.foreign_amount-= money;  NSLog (@ "Current foreign currency (%c) account balance after withdrawal:%.2LF", type,self.foreign_amount);  return self.foreign_amount;} @end

Account_dollar.h file

#import "Account.h" @interface account () {  char _currency_type;  Double _foreign_rate;  Double Foreign_amount;} @property (assign) char currency_type; @property (assign) double foreign_rate; @property (assign) Double foreign_amount;@ End

OC language-inheritance, dot syntax, category

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.