The three major characteristics of the---Class of OC learning (encapsulation, inheritance, polymorphism)

Source: Internet
Author: User
Tags modifiers

A previous article describes the initialization method and the use of the point syntax for classes in OC: http://blog.csdn.net/jiangwei0910410003/article/details/41683873, today to continue learning the three main features of the class in OC , we know in Java, the class has three major features: inheritance, encapsulation, polymorphism, this is the introduction of the class, it must mention the topic, then today to look at the three main features of OC class:


First, the package

Students who have studied Java classes may know that encapsulation is a class of some fields, methods to protect, not to be accessed by the outside world, there is a control function, Java has four kinds of access modifiers:public,default,protected, Private, access permissions are decremented once, so that when we define the class, which fields and methods do not want to be exposed, which fields and methods can be exposed, can be done by modifiers, this is the encapsulation, let's look at an example:

Car.h

  car.h//  05_objectdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import <Foundation/Foundation.h> @interface car:nsobject{    // This property is the equivalent of private, so we need external access, we must define the Get/set method    //default is private, but we can use @public set to the public property, Then the external can be directly accessed: person->capcity = 2.8;    Of course, we generally do not use this, because this will destroy the encapsulation, this usage is equivalent to the struct in C    //Altogether four kinds: @public, @protected, @private, @package, this is the same as in Java @public    float _capcity;//Oil quantity attribute}-(void) Run: (float) t; @end
As we can see here, there are also four types of access modifiers in OC:

@public, @protected, @private, @package

Where the default modifier is @private

However, it is important to note that the method in OC is not the concept of modifiers, this and Java has a great difference, is generally publicly accessible, that is, public, but how do we make a method in OC can not be accessed by the outside world?

This is done in OC, if you want a way to not be accessed by the outside world, Only need to implement this method in the. m file, do not define in the header file, it is said: The method is implemented, not defined, so that the outside world in the import of the header file, there is no such method, but this method can be used in their own. m files.

Why do you want to introduce this knowledge? Because in the back we will talk about the simple interest mode, then we will use this knowledge point.


Ii. inheritance

Inheritance is an important feature of the class, and his presence makes it unnecessary to write repetitive code, which is highly reusable. Of course, the inheritance in OC and Java is the same, not much difference, here is looking at an example:

First look at the parent class: Car

Car.h

  car.h//  06_extenddemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import <Foundation/Foundation.h> @interface car:nsobject{    nsstring *_brand;    NSString *_color;} -(void) Setbrand: (NSString *) brand;-(void) SetColor: (NSString *) color;-(void) brake;-(void) Quicken; @end
Two properties are defined in the car class, and some methods

Car.m

  car.m//  06_extenddemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Car.h" @implementation car-(void) Setbrand: (NSString *) brand{    _brand = brand;} -(void) SetColor: (NSString *) color{    _color = color;} -(void) brake{    NSLog (@ "brake");} -(void) quicken{    NSLog (@ "acceleration");} @end
Implementation of the method


In a look at the sudden class:

Taxi.h

  taxi.h//  06_extenddemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Car.h" @interface taxi:car{    nsstring *_company;//company}//Print Invoice-(void) Printtick; @end
See the taxi class inherits the parent class car, where you need to import the parent class's header file, and then one more property and method in the taxi class

Taxi.m

  taxi.m//  06_extenddemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Taxi.h" @implementation taxi-(void) printtick{    [Super brake];    [Self brake];    NSLog (@ "%@ Taxi printed the invoice, the company is:%@, Color:%@", _brand,_company,_color);} @end
For the implementation of the method, we see here that the implementation file does not need to import the parent class car header file, because you can think that the Taxi.h header file already contains car's header file. Moreover, the Super keyword can be used here to invoke the parent class method, and here we can also use the Self keyword to invoke, here see actually the two methods of invocation of the effect is the same, when we re-implement the brake method in the sub-class (the rewriting concept in Java), So this time the Super keyword calls the method of the parent class, and self calls the brake method after the rewrite. Similarly, we can also use attributes from the parent class.


Let's look at another subclass:

Truck.h

  truck.h//  06_extenddemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Car.h"//Truck class inheritance Car@interface truck:car{    float _maxweight;//Max cargo capacity}//override the parent class method brake// A method that prioritizes the invocation of subclasses-(void) brake;-(void) unload; @end
Here you define a brake method, which overrides the brake method in the parent class.

Truck.m

  truck.m//  06_extenddemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Truck.h" @implementation truck-(void) brake{    [Super brake];    NSLog (@ "Brake method in Truck Class");} -(void) unload{    [Super brake];//method of calling the parent class    [self brake];//is also possible    NSLog (@ "%@ truck unloading, cargo capacity:%.2f, car color:%@", _ Brand,_maxweight,_color);} @end
As you can see here, we will invoke the brake method of the parent class in the brake method, and then implement our own logic code.


Well, inheritance is said so much, in fact, encapsulation and inheritance of two features is not difficult, it is easy to understand, the following look at the last feature: polymorphic


Three, polymorphic

Polymorphism for the object-oriented thinking, the personal feeling is really important, he will be writing code in the elegant way also plays a very important role, in fact, many of the design patterns are used in most of the characteristics of polymorphic, Java in the polymorphic features used is very convenient, but C + + is very difficult to use, In fact, many states are: the definition of the type and the actual type, is generally based on the form of interface implementation, not to mention, directly see examples:

Examples of printers

Abstract Printer Class Printer

Printer.h

  printer.h//  07_dynamicdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei . All rights reserved.//#import <Foundation/Foundation.h> @interface printer:nsobject-(void) print; @end
is a simple way to print

Printer.m

  printer.m//  07_dynamicdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Printer.h" @implementation printer-(void) print{    NSLog (@ "Printer printing paper");} @end
The implementation is also very simple


Here's a look at the specific subclass

ColorPrinter.h

  colorprinter.h//  07_dynamicdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Printer.h"//Modify the print behavior of the parent class @interface colorprinter:printer-(void) print; @end


COLORPRINTER.M

  colorprinter.m//  07_dynamicdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "ColorPrinter.h" @implementation colorprinter-(void) print{    NSLog (@ "Color Printer");} @end

Take a look at another subclass

BlackPrinter.h

  blackprinter.h//  07_dynamicdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Printer.h" @interface blackprinter:printer-(void) print; @end

BLACKPRINTER.M

  blackprinter.m//  07_dynamicdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "BlackPrinter.h" @implementation blackprinter-(void) print{    NSLog (@ "Black and white Printer");} @end


Here we are defining a person class that is used to manipulate the specific printer

Person.h

  person.h//  07_dynamicdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import <Foundation/Foundation.h> #import "ColorPrinter.h" #import "BlackPrinter.h"// Scalability is not high, when we need to add a new printer to define a corresponding method//So this time you can use polymorphic technology @interface person:nsobject{    nsstring *_name;} -(void) Printwithcolor: (Colorprinter *) colorprint;//-(void) Printwithblack: (Blackprinter *) blackprint;-(void) Doprint: (Printer *) Printer; @end


person.m

  person.m//  07_dynamicdemo////  Created by Jiangwei on 14-10-11.//  Copyright (c) 2014 Jiangwei. All rights reserved.//#import "Person.h" @implementation person/*-(void) Printwithcolor: (Colorprinter *) colorprint{    [colorprint print];} -(void) Printwithblack: (Blackprinter *) blackprint{    [blackprint print];} */-(void) Doprint: (Printer *) printer{    [printer print];} @end

Let's take a look at the test code:

Main.m

main.m//07_dynamicdemo////Created by Jiangwei on 14-10-11.//Copyright (c) 2014 Jiangwei. All rights reserved.//#import <Foundation/Foundation.h> #import "Person.h" #import "BlackPrinter.h" #import " ColorPrinter.h "int main (int argc, const char * argv[]) {@autoreleasepool {person *person =[[person all                OC] init];        Colorprinter *colorprint = [[Colorprinter alloc] init];                Blackprinter *blackprint = [[Blackprinter alloc] init];        Polymorphic definition/* Printer *P1 = [[Colorprinter alloc] init];                Printer *P2 = [[Blackprinter alloc] init];        [Person DOPRINT:P1];         [Person DOPRINT:P2];        ////////control which printer int cmd is used by the command entered by the console;            do{scanf ("%d", &cmd);            if (cmd = = 1) {[Person doprint:colorprint];            }else if (cmd = = 2) {[Person doprint:blackprint];            }}while (1); } return 0;}


Here is a detailed explanation of the benefits of polymorphism

The above example is a color printer and a black and white printer both printers, and then the person class has a method of printing, of course, this method requires a Printer object, if not implemented by the polymorphic mechanism (Person.h in the code part of the comment), is to define a separate operation for the two printers, and then use the specific Printer object in the PERSON.M (the part of the comment in the code), and in the main.m file, we see that the specified method is called when the person needs to use which printer:

[Person printwithblack:blackprint];//call black-and-white printer [person printwithcolor:colorprint];//call Color Printer
This design is not good, why? If there is another printer now, then we need to define a way to operate the printer in Person.h, so what if we add a new printer later? Are you still adding a method? Then the Person.h file becomes bloated. So this time polymorphism is good, using the parent class type, define a method in Person.h:

-(void) Doprint: (Printer *) Printer;
Here we see that the parameter type of this method is the type of the parent class, which is polymorphic, the definition type is the parent class type, the actual type is the subclass type

-(void) Doprint: (Printer *) printer{    [Printer print];}
The Print method is called here, which is the actual type of print method passed in.

Printer *P1 = [[Colorprinter alloc] init]; Printer *P2 = [[Blackprinter alloc] init];        [Person DOPRINT:P1]; [Person DOPRINT:P2];
The type on the P1,P2 surface here is printer, but the actual type is the subclass type, so it calls their own corresponding print method.


From the above example, we can see the polymorphism of the new is very important, of course, the three major characteristics of the more difficult to understand, but in the process of coding, with more natural understanding, there is no need to deliberately understand.


Summarize

This article mainly introduces the three main characteristics of the class: encapsulation, inheritance, polymorphism, these three features are also the important basis behind learning object-oriented.

















The three major characteristics of the---Class of OC learning (encapsulation, inheritance, polymorphism)

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.