Dark Horse Programmer------OC Object-oriented encapsulation

Source: Internet
Author: User

---Android training, iOS training, Java training, and look forward to communicating with you-----


I. Object-oriented and encapsulation

Object-oriented three major features: encapsulation, inheritance, polymorphism.

Encapsulation is the main feature of object and class concepts. It is a hidden internal implementation that stabilizes the external interface and can be seen as a "wrapper". Encapsulation, which is the encapsulation of objective things into abstract classes, and classes can put their own data and methods only trusted class or object operation, to the untrusted information hiding.
Benefit: More secure with simpler variables to hide internal implementation details development is faster.

In Apple's official document, there is a picture illustrating the package vividly:


@interface is used to show people the time, to provide the external display and API interface, @implementation is the internal implementation, people do not need to know how the clock inside how to operate, the same developers do not have to care about how the class, object methods are implemented, Just call the API method to complete the function.


Second, set method

when we encapsulate good one objects, for security reasons, developers often do not want others to have direct access to the member variables in their design classes that can be arbitrarily accessed by outsiders. For example, there is a member variable in the person class, age, which can have unpredictable consequences when used to assign a negative number to age, at which point the developer must privatize the attribute (with @private), and provide an externally accessible method for that property. For the visitor to modify the age, then the set method is born.

Set method function : Used to set the member variable value, can be in the set method, unilaterally filter out some of the illegal, unreasonable values, improve the robustness of the system.


Set method naming specification:

1) method name must start with set

2) The set is followed by the member variable name, and the first letter of the member variable must be capitalized; for example: Setage

3) The return value must be void

4) Be sure to receive a parameter that must be of the same type as the member variable, and that the parameter is best not to have the same name as the member variable


the benefits of the Set method :

1) Keep the data safe by not exposing the member variables to some extent

2) Check and filter the data submitted by the user.


code example:

The Set method declaration section:

/* 4. Design a score class * C language score (readable and writable) * OC score (readable and writable) * SCORE (Read only) * average (Read only) * * #import <Foundation/Foundation.h> @interface score:nsob ject{    int _cscore;//C language score    int _ocscore;//OC score        int _totalscore;//score    int _averagescoe;//Average Division}-(void) s Etcscore: (int) cscore;-(void) Setocscore: (int) Ocscore; @end


The Set method implementation section:

@implementation score-(void) Setcscore: (int) cscore{    _cscore = Cscore;        Calculate Total score    _totalscore = _cscore + _ocscore;    _averagescoe = _TOTALSCORE/2;} -(void) Setocscore: (int) ocscore{    _ocscore = Ocscore;        Calculate Total score    _totalscore = _cscore + _ocscore;    _averagescoe = _TOTALSCORE/2;} @end


To run the program:

#import <foundation/foundation.h>int Main () {    score *s = [score new];        [s setcscore:90];    [s setocscore:100];        [s setcscore:80];            return 0;}


Third, Get method

As mentioned above, the programmer has security considerations to privatize member variables, then in the class design, you must provide a method for the caller to obtain the corresponding member variables, the Get method is generated.

What The Get method does: returns the member variable inside the object

Get method Naming specification:

1) The Get method name is generally the same as the member variable name

2) must have a return value, and the return type must match the member variable

3) No need to receive any parameters

Code examples (together with the Set method):

The Declarations section of the Get method:

#import <foundation/foundation.h>typedef enum {    Sexman,    Sexwoman} Sex; @interface student:nsobject{/* Naming conventions for member variables: Be sure to start with the following lines  :  1. Distinguish the member variable from the name of the Get method  2. Can be separated from the local variables, a variable that sees the beginning of the underscore, is usually the member variable  */    int _no;    Sex _sex;} The set and get methods for Sex-(void) Setsex: (Sex) sex;-(sex) sex;//no set and Get methods-(void) Setno: (int) no;-(int) No; @end


The Get Method implementation section:

@implementation student-(void) Setsex: (Sex) sex{    _sex = sex;} -(Sex) sex{    return _sex;} -(void) Setno: (int) no{    _no = no;} -(int) no{    return _no;} @end


To run the program:

#import <foundation/foundation.h>int Main () {    Student *stu = [Student new];        [Stu Setsex:sexman];    [Stu Setno:10];        [Stu Sex];        [Stu No];        return 0;}


Note the point:

The design of a class does not have to provide a setter method and getter method for each member variable, such as a member variable, the designer only wants to let the caller access, but do not want to be modified, then only need to provide getter method, very flexible.


Iv. Types of methods

1) Basic Concepts

A class method can be called directly by the class name without generating an object.

2) class method VS object Method

The ① object method name starts with a-and the class method starts with a +

② object methods can only be called by objects, no objects, object methods cannot be called, class methods can only be called directly by the class and cannot be called by an object

③ Object methods can access member variables, class methods cannot access member variables


the benefits and uses of the class method:
1> is not dependent on the object, the execution efficiency is high
2> can use class method, try to use class method
3> Occasions: You can change to a class method when you do not need to use a member variable inside a method

you can allow class methods and object methods to have the same name

code example:

#import <Foundation/Foundation.h> @interface person:nsobject{    int age;} Class methods are preceded by + (void) printclassname;-(void) test;+ (void) test; @end @implementation person+ (void) printclassname{    / /error:instance variable ' age ' accessed in class    method//Instance variable "The class cannot access the    //nslog (@" This class is called person-%d ") -(void) test{    NSLog (@ "111-%d", age);        [Person test];} + (void) test{    //will cause a dead loop    //[person test];        NSLog (@ "333");        Will cause a dead loop//    /[person test];} @endint Main () {    //[person printclassname];        [Person test];        Person *p = [person new];    [P test];     /*-[person Printclassname]: Unrecognized selector sent to instance 0x7fa520c0b370     *//    / The system will assume that the printclassname called now is an object method    //[p Printclassname];        return 0;}


Five. Self keywords

Self is a pointer to the current caller, who calls, and self points to who.

* Self appears in the object method, and self represents the object
* Self appears in the class method, and self represents the class

Use of self:

1) Access member variables with the SELF keyword to differentiate local variables with the same name

2) Use [self method name] to invoke method


code example:


#import <Foundation/Foundation.h> @interface dog:nsobject-(void) bark;-(void) run; @end @implementation dog-( void) bark{    NSLog (@ "Wang Woo");} -(void) run{    [self bark];    NSLog (@ "Wang Bark");    NSLog (@ "Run and Run");} @endint Main () {    dog *d = [dog new];        [D run];        return 0;}




Dark Horse Programmer------OC Object-oriented encapsulation

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.