Three features such as Objective-C: encapsulation, inheritance, and polymorphism (1)
As we all know, classes in Object-Oriented Programming have three major features: inheritance, encapsulation, and polymorphism. This is also a topic that must be mentioned when introducing classes, let's take a look at the three main features of classes in OC today:
I. Encapsulation
Encapsulation is to protect some fields and methods in the class from being accessed by the outside world. It has a permission control function. Java has four access permission modifiers:
public,default,protected,private
The access permissions are decreased in turn, so that when we define the class, which fields and methods do not want to be exposed, which fields and methods can be exposed, and can be done through modifiers. This is encapsulation, here is an example:
Car. h
// Car. h // 05_ObjectDemo /// Created by jiangwei on 14-10-11. // Copyright (c) 2014 jiangwei. all rights reserved. // # import @ interface Car: NSObject {// This attribute is equivalent to private, so if we need to access it externally, the get/set method must be defined. // The default value is private. However, you can use @ public to set it to the public attribute. You can directly access: person-> capcity = 2.8 externally; // of course, we generally do not use this method because it will damage encapsulation. This method is equivalent to the permission in the struct in C. // there are four types in total: @ public, @ protected, @ private, @ package, which is the same as @ public float _ capcity in Java; // fuel quantity attribute}-(void) run :( float) t; @ end
Here we can see that there are four access permission modifiers in OC:
@public、@protected、@private、@package
The default modifier is @ private.
However, it should be noted that the methods in OC do not have the modifier concept. This is very different from Java, and is generally publicly accessible, that is, public, but how can we prevent a method in OC from being accessed by the outside world?
In OC, if you want to prevent a method from being accessed by the outside world, you only need. to implement this method in the m file, do not define it in the header file. To put it bluntly, this method is implemented and not defined. This method is unavailable when the header file is imported, however, we can use this method in our own. m file.
Why should we introduce this knowledge? Because we will talk about the single-profit model later, and we will use this knowledge point in time.