(Post) Encapsulation of objects and class C # In "Open the Door of C #"

Source: Internet
Author: User

3. Object encapsulation and C # class

Object-oriented thinking has three core elements: encapsulation, inheritance, and polymorphism. If we can correctly understand these three elements, we can basically establish an object-oriented idea in programming. In section 2, I introduced that in section C #, all data-type instances are "objects", but the types that best reflect the characteristics of objects are still "classes ", it is also the most important and frequently used type in C. Next, I will introduce the C # class to fully understand the concept of object encapsulation.

The so-called "object", in an image, can be understood as a block. The people who design the building blocks need to design the appearance and shape of the building blocks, as well as internal materials. People who pile up wood do not care about internal materials. They only need to decide the stacking position based on different appearances and shapes. Therefore, for developers, it is necessary to design object-oriented programs, and there will be two very different identities: designers and users.

First, let's talk about users. The user's identity is to use all the objects that have been provided to you to design the programs you need to implement as needed. This is like the accumulation of wood. This is precisely the advantage of object-oriented programming, that is, "Object reuse ". Objects that have been designed can be called by different users. Since these functions have been implemented, the process of self-design is of course avoided for users. As with accumulation of wood, since there is a ready-made building block, the user's job is to combine these building blocks to form different shapes .. The class library provided by net framework is such a building block.

For example, if we want to convert an int type to the struct type, there is no need to implement this conversion on our own. NET Framework can directly call the functions provided:
Int I = 10;
String S = I. tostring ();

For example, if you want to bring up a Windows message box, you can directly use the. NET Framework existing Class Library:
MessageBox. Show ("message ");

In the preceding example, I and MessageBox are both objects.

Let's talk about the identity of the designer. Although the class library function of. NET Framework is very powerful, it cannot take into account all aspects of the business. If you need to use an object that does not exist at all, you need to design it yourself. The example book management system may require users, books, and other objects. This requires developers to design these objects themselves.

Since the type that best embodies the "object" idea is "class", let me introduce the class type in C. The class keyword in C # is class. In a class object, it is mainly divided into field, property, and method. The first two correspond to the attributes of the object, while method corresponds to the behavior of the object. A typical class is defined as follows:
Public class user
{
Private string m_name;
Private string m_password;
Private int m_trycounter;
Public string name
{
Get {return m_name ;}
Set {m_name = value ;}
}
Public String Password
{
Get {return m_password ;}
Set {m_password = value ;}
}
Public void signin ()
{
If (m_trycounter <3)
{
If (isvalid ())
{
M_trycounter = 0;
Console. writeline ("User {0} was signed in.", m_name );
}
Else
{
M_trycounter ++;
Console. writeline ("User {0} is invalid. Can't sign in.", m_name );
}
}
Else
{
Console. writeline ("You try to sign in more than 3 times. You are be denied .");
}
}
Public void signout ()
{
M_trycounter = 0;
Console. writeline ("User {0} was signed out.", m_name );
}
Private bool isvalid ()
{
If (m_name.toupper () = "admin" & m_password = "admin ")
{
Return true;
}
Else
{
Return false;
}
}
}

The m_name, m_password, and m_trycounter strings are user-like fields. name and password are user-like attributes, while signin, signout, and isvalid are user-like methods.

For field, property, and method, I will introduce them in subsequent articles. Here we will mainly introduce the Public and Private modifiers in this class.

As mentioned above, the object is like a building block. Designers need to define the appearance and shape of the building block, and also consider the internal building blocks, such as the selected materials and whether they are hollow or solid. If you open this building block, the object should be divided into two layers: inside and outside. Because users only care about external implementations, designers need to consider which implementations should be exposed and which ones should be hidden. This reflects the idea of object encapsulation.

The encapsulated object is not to completely package the entire object, but to set user access permissions according to specific needs. In C #, public, internal, protected, and private modifiers are used to modify the fields, attributes, and methods of the class, and even the class object itself:
Public: indicates that all objects can be accessed;
Protected internal: indicates the object in the same assembly, or the class object and its subclass can be accessed;
Internal: indicates that only objects in the same assembly can be accessed;
Protected: indicates that only the class object and its subclass objects can be accessed. (inheritance will be introduced later)
PRIVATE: indicates that only the object itself can be accessed within the object;

We can see that public is the most open, followed by protected internal, and private is the least open. Center internal and protected. Which of the following is the scope of internal and protected? In my opinion, there is no absolute conclusion. Their scope reflects a horizontal concept, while the latter reflects a vertical concept. If it is internal, the external Assembly object is naturally inaccessible, but as long as it is in the same assembly, all objects can access it; if it is protected, then even the external Assembly object, as long as it inherits the object, it can be accessed. Even if the object is not a subclass of this class object in the same assembly, it cannot be accessed. For example, in our traditional culture, we place great emphasis on the concept of "clan". The patriarch of a clan has a great deal of power for their own people and even master the power of killing and killing. Taking the scope of a state as an example, internal is like an adult in the State. As long as it is the people in the state, it belongs to his jurisdiction, regardless of his clan. Protected is like a clan leader. As long as it is a member of the clan, it must obey him, even if the member belongs to another State. I have read the Yong Zheng Dynasty before, and there is such a plot in it. As the Emperor's son, he cannot save the fate of his beloved woman because this woman violates the family rules of their clan, in the end, she was burned to death, but she was only stunned.

All fields m_name, m_password, and m_trycounter are private in the user class defined previously. Therefore, external callers of the user class cannot call them, note that the internal methods of the user class, such as signin or attribute name, can be called completely. Similarly, the private method isvalid can be called by the signin method, but it cannot be called by external callers. For the public attributes name, password, and public methods signin and signout, external callers can access them. In the subsequent drills, we can see the difference between them. Through hierarchical encapsulation, the reusability and security of objects can be fully guaranteed.

So how do I determine their access permissions for the class type? This is based on actual needs. Assume that this user class is used for an e-commerce website. In the design process, e-commerce systems need to call user-class objects. Obviously, the login and exit functions must be provided to external users. For example, the logon page will use the user class. The isvalid () method is used to verify the validity of a user. It is also necessary, but it is only used to verify the identity of a user during logon. That is to say, the isvalid method is only used by the signin method, however, external users do not care about it. Therefore, setting it to private is reasonable. The same applies to the m_trycounter field. However, if the requirement changes, the function of verifying the user is not only required for login, but also required for adding products to the shopping cart, placing orders, and making payments, the isvalid method, it is necessary to change it to the public method.

Therefore, when designing a program, in addition to recognizing an object, we also need to fully consider the encapsulation of this object. Fields, attributes, and methods in class objects, including the class itself, which should be exposed, and which should be hidden, must be correctly designed according to actual needs.

Drill:
(1) design class user and call this class
1. Open Visual Studio. NET, select "new" from the "file" menu, and select "project ";
2. Select "console application" in Visual C # projects ". In location, locate the path of the project you want to save, and the name is "secondexample ". This name is both the solution name and the project name.
3. Right-click the project name. In the displayed dialog box, name the Assembly name secondexample and the default namespace brucezhang.com. secondexample.
4. Right-click the project name and select "add class" in the "add" menu item ":
 

5. In the displayed dialog box, name the file user. CS,
 

6. Click "open". A new file user. CS is added to the project. Open the file and change the content in the public class user to the user class defined previously.
7. modify the original default class1.cs (if it is Visual Studio 2005, it is program. cs by default) file name to app. CS, and then modify the file content:
Class app
{
/// <Summary>
/// The main entry point for the application.
/// </Summary>
[Stathread]
Static void main (string [] ARGs)
{
User user = new user ();

// The user name and password are both incorrect;
User. Name = "Bruce ";
User. Password = "test ";
For (INT I = 0; I <= 4; I ++)
{
User. signin ();
}
User. signout ();

// The user name is correct and the password is incorrect;
User. Name = "admin ";
User. Password = "test ";
For (INT I = 0; I <= 4; I ++)
{
User. signin ();
}
User. signout ();

// The user name and password are correct;
User. Name = "admin ";
User. Password = "admin ";
For (INT I = 0; I <= 4; I ++)
{
User. signin ();
}
User. signout ();

// Note that such fields and methods cannot be called at this time;
// User. m_name;
// User. m_password;
// User. isvalid ();

Console. Readline ();
}
}
8. Run.

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.