Getting started with iOS development☞OC Language & #183; note 6, iosoc

Source: Internet
Author: User

Getting started with iOS development☞OC language · note 6, iosoc
Three main features of object-oriented: encapsulation, inheritance, polymorphism 1. Encapsulation

1.1 Basic Concepts

Combine scattered things.

  • In a broad sense, encapsulation refers to encapsulating code into functions, instance variables and methods into classes, and classes into frameworks ....
  • Encapsulation in object orientation refers to the interface that encapsulates attributes and methods in an object and only exposes access to the outside world, and hides the specific implementation.

1.2 encapsulation benefits

Improve readability, maintainability, and scalability

Encapsulation in 1.3 OC

The OC language is encapsulated.

When defining a class, the @ interface part is an access interface made public to the outside world. @ Implementation is the specific implementation of hiding.

In the. h file, public interfaces are written.

The. m file contains hidden implementations.

// Private method, as long as the method is not declared in the header file Interface part, it is a private Method

2. Inheritance

2.1 concepts

Inheritance is a code reuse technique (code reuse ). Is a relationship between classes ("is a" relationship ).

Class B inherits Class. Class A is the parent class of Class B, and Class B is the subclass of Class.

Other languages also have the concept of base classes and derived classes.

2.2 Inheritance Method

Single inheritance OC, Java..., Swift single inheritance means that a class can only have one parent class.

Multi-inheritance C ++ supports multi-inheritance means that a class can have multiple parent classes.

Classes in the OC language are on a tree with only one NSObject ancestor. swift has not only one tree but also one forest.

2.3 syntax inherited from OC

@ Interface Class Name: parent class name

 

@ End

2.4 When inheritance is used

Theoretically:

If the two classes have an is-a relationship, the two classes should have an inheritance relationship.

The Dog is an Animal Dog is a Animal.

Animal is the parent class, and Dog is the subclass.

If the two classes have a has a relationship, they should be combined or aggregated.

Computing has a CPU: Computer has a CPU

Combination and aggregation are the relationship between another type and class.

Use inheritance in actual development:

Is the parent class written first or the Child class written first? // Yes

 

2.5 abstract class

C ++: pure virtual functions without function bodies. Classes with pure virtual functions are abstract classes and objects cannot be instantiated.

Java: abstract methods and abstract classes.

OC: The OC language does not have the syntax of abstract classes and abstract methods.

Derivation: Add new attributes and methods to the subclass.

2.6 rewrite: If the subclass is not satisfied with the method of the parent class, you can override the method in the parent class.

Hide: When the subclass overrides the parent class method, there will be two methods with the same name in the subclass. Methods inherited from the parent class cannot be called outside the class.

2.6.1 concepts

1) override rewriting (overwrite): The subclass is not satisfied with the method inherited from the parent class, and this method is implemented again.

Requirement: The method is the same as the parent class, the parameter type is the same, and the return value is the same. Only methods are implemented differently.

2) overload: There is no overload in OC.

The concept of overload is that multiple methods with the same name exist in a range (for example, in a class). The parameter types of these methods are different, so they can appear at the same time. Let's say, these methods form an overloaded relationship.

In OC, multiple methods with the same name in the same range are not allowed.

-(Id) initWithName :( NSString *) name andAge :( NSUInteger) age;

-(Id) initWithName :( NSString *) name andGender :( BOOL) gender; // The Chinese domain name of OC is different

Only rewriting is performed in OC, and no Overloading is performed.

Method Rewriting: The subclass is not satisfied with the method inherited by the parent class. You can override the method of the parent class in the subclass.

If you override the method of the parent class, the subclass method is preferentially called. If the subclass does not override the method of the parent class, the method of the parent class is called.

 

2.6.2 note

Although the attributes in the parent class are public, the generated instance variables are private and cannot be accessed in the subclass.

2.6.3 rewriting of common methods

Like perimeter, area, show

The method name is the same, the parameter type is the same, and the return value is the same

2.6.4 rewrite attributes

Like the width and height attributes in TRSqaure

2.6.5 inheritance and rewriting of special methods

1) initialization method

The initialization method in OC will be inherited.

Some of the inherited initialization methods can be used, and some cannot be used.

If the initialization method inherited from the parent class is unavailable in the subclass (the required initialization task cannot be completed), you need to override this initialization method in the subclass.

2) class method (Factory method)

Class methods can also be inherited

The factory method can also be inherited, but the factory method name directly inherited does not match, which is rarely used in actual development. Sub-classes are recommended to provide their own factory methods.

2.7 inheritance Defects

1) increases the complexity of the program, reduces maintainability and scalability.

2) use inheritance with caution for the encapsulation of damage classes!

2.8 why inherit?

1) code reuse

Abstract The repeated code of the subclass into the parent class.

2) develop specifications (Rules)

NSObject

3) For Polymorphism

No polymorphism without inheritance

Combination and aggregation

A common relationship between classes. Its main role is code reuse!

1.1 What is combination?

It indicates the strong relationship between two objects and the whole part. It is a "contains (included) a" relationship, and two classes must coexist.

The life cycle is exactly the same. Some lifecycles cannot exceed the overall level!

For example, a window contains buttons and labels. When the window is closed, the window is destroyed together with the buttons and labels.

 

1.2 Definition of a combination:

@ Interface BRButton: NSObject

@ End

@ Interface BREdit: NSObject

@ End

@ Interface BRWindow: NSObject

/**

* A combination is strongly related to two classes (which must be defined as a member variable)

* 1. assign values to instance variables during object initialization (same life and death)

* 2. You cannot access or assign values to instance variables outside the class.

*/

{

BRButton * button;

BREdit * edit;

}

@ End

 

Combined Demo:

    

    

1.3 advantages and disadvantages of the combination:

Advantages:

1) The current object can only call its method through the included object, so the internal details of the contained object are invisible to the current object.

2) The current object has a low coupling relationship with the contained object. If you modify the code in the class containing the object, you do not need to modify the code of the current object class.

3) The current object can be dynamically bound to the objects contained at runtime. The set method can be used to assign values to included objects.

Disadvantages:

It is easy to produce too many objects.

To combine multiple objects, you must define the interface carefully.

 

1.4 What is Aggregation

It indicates the weak relationship between two objects and the whole part. It is a "has a" relationship, and two classes are not required to coexist.

Different lifecycles make one class unable to control the life and death of another class. Some lifecycles can surpass the whole.

For example, when a computer or a mouse is destroyed, the mouse can be left on another computer for further use.

1.5 definition of aggregation

@ Interface BRMouse: NSObject

@ End

@ Interface BRComputer: NSObject

// Aggregation is a weak relationship between two classes. It assigns values to instance variables outside the class (which must be defined as attributes)

@ Property BRMouse * mouse;

@ End

 

Aggregate Demo:

    

1.6 Advantages and Disadvantages of aggregation:

Advantages:

1) The contained objects are accessed through the classes that contain them.

2) Good Encapsulation

3) The internal details of the contained object are invisible.

4) You can dynamically define the aggregation mode at runtime.

Disadvantages:

1) The system may contain too many objects.

2) When using different objects, you must be careful with the interface defined.

The life cycle of a combination is different from that of an aggregation. A combination is active and dead (closely related). There is no special relationship between aggregation.

 

There are three common relationships between 1.7 classes and classes: inheritance, combination, and aggregation.

1) Inheritance (the main purpose of inheritance: code reuse, specification, for polymorphism) Use inheritance with caution! (Inheritance is used only when the is relationship is established; otherwise, inheritance is abused)

2) combination and aggregation (simply for code reuse)

The main purpose of combination and aggregation is to reuse code.

Application Scenario: (code reuse. If you want to use others' code, you can combine and aggregate them)

In actual development, to reuse code, combination or aggregation is recommended, instead of inheritance. That is, one class is used as the attribute of another class. (Overall and partial)

 

How does one class want to use another class? How to Implement...

1. Inheritance: If I inherit from you, I can directly tune your method (increase the complexity of the program... Not recommended !)

2. Combination/aggregation: it turns you into a part of me (that is, you are my attribute), and I can access you to call your method! [Me. Your method];

 

Combination: the relationship is very close, and they are both born and dead. (When the cpu is soldered to the motherboard, the cpu will be broken when the motherboard is broken; when it is tied together, it will die together !)

Aggregation: the relationship is very distant, and they are not born together. (The computer is a computer, and the cpu is a cpu. The cpu can be used for this computer, or for that computer. The cpu can be pulled from the motherboard for another computer)

3. Polymorphism (Polymorphism)

3.1 What is polymorphism

Multiple forms, multiple forms of reference. A referenced variable can point to any class Object (one external interface and multiple internal implementations)

 

The reference of the parent class points to the object of this class or any subclass and calls different methods (multiple forms are shown, which are called polymorphism)

TRAnimal * animal = [[TRDog alloc] init]; // reference of the parent class to the subclass object

[Animal eat]; // specifies the method to rewrite a Child class)

Animal = [[TRCat alloc] init];

[Animal eat]; // cat eats fish

Polymorphism: The same referenced variable s calls the same method (show) to display different results.

TRShape * s = [[TRRect alloc] init]; // reference of the parent class to the subclass object

[S show]; // display the rectangle. Call the subclass override method.

S = [TRCircle alloc] init];

[S show]; // display the circle

 

3.2 types during compilation and Runtime

During compilation, the referenced type is called the compilation period type.

When the program is running, the referenced type is the runtime type.

       

During program compilation, find the method by the type during the compilation period, and find the method call by the type during the runtime when the program is running.

When a parent class references an object pointing to a subclass, it can only call methods in the parent class.

The compiler checks the method by the parent class during compilation. Although the Sub-class method is called during runtime, the method is checked by the parent class during compilation.

3.3 why Polymorphism

Why use the reference of the parent class to point to the object of the subclass:

In order to write code that is more usable (generic) and more compatible.

 

3.4 manifestations of polymorphism [PURPOSE]

1) [parameter polymorphism] The parameter polymorphism is often manifested in methods: the parameter type uses the parent type and can be passed to any subclass object.

The difference between NSObject * and id type as a method parameter is:

NSObject * type references can only call methods in the NSObject class.

An id reference can call any method that exists (cannot be written blindly.

(Generally, the NSObject * type is not used, and the id type is used instead. Id is risky. The Compiler does not check right or wrong)

/** Method parameter presentation polymorphism */

Void showAnimal (TRAnimal * animal ){

[Animal eat];

[Animal sleep];

// [Animal watchHome]; // The parent class does not use this method for compilation and does not pass

}

Int main (){

@ Autoreleasepool {

TRDog * dog = [[TRDog alloc] init];

ShowAnimal (dog );

ShowAnimal ([TRCat new]);

}

Return 0;

}

 

2) [return value polymorphism] the return value of the method represents polymorphism.

    

3) [array polymorphism] polymorphism in arrays and collections

// Polymorphism of array representation [multiple objects execute the eat method at the same time]

TRAnimal * animals [3] = {[TRAnimal new], [TRDog new], [TRCat new]};

For (int I = 0; I <3; I ++ ){

[Animals [I] eat];

}

Polymorphism is everywhere!

 

 

Multi-state Demo

  

    

    

 

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.