C # Learning Diary----encapsulation and access modifiers

Source: Internet
Author: User

Packaging:

is defined as "enclosing one or more items in a physical or logical package". In the object-oriented programming methodology, encapsulation is designed to prevent access to the implementation details. That is, the implementation of the details inside the package, so that a very complex logic after packaging for others to use is very convenient, others do not need to understand how the inside is implemented, as long as the required parameters to get the desired results. Encapsulation is implemented by using access modifiers. An access modifier defines the scope and visibility of a class member.

Access modifiers:

In the Declaration and definition of class classes I briefly introduced the access modifier, not very specific, here we delve into the access modifier;

Access modifiers in C # have 5 public, private, protected, internal, protected internal;

public modifier

The public access modifier allows a class to expose its member variables and member functions to other functions and objects. Any public member can be accessed by an external class. (Does not restrict access to members, subclasses can, objects can also)

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;    Namespace Test  {      class student      {public          int chinese=80;          public int math=67;          public int english=45;           Defines a method public          int Total ()          {              int sum = 0;              sum = Chinese + Math + 中文版;              return sum;          }      }      Class teacher      {          static void Main (string[] args)          {              student stu = new student ();  Instantiate an object              Console.WriteLine ("Chinese = {0}\nmath = {1}\nenglish = {2}\ntotal = {3}", Stu. Chinese,stu. Math,stu. English,stu.total ());}}}  

Output Result:

In the example above, all the members in student are public type access, so his instantiated object Stu has access to all members.

Private modifier

The Private access modifier allows a class to hide its member variables and member methods from his objects. Only a method in the same class can access its private members. Even an instance of a class cannot access its private member (it does not allow access to his child classes or objects).

We use the above example to:

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;    Namespace Test  {      class student      {          private int chinese=80;          private int math=67;          public int english=45;            private int Total ()          {              int sum = 0;              sum = Chinese + Math + 中文版;              return sum;          }      }      Class teacher      {          static void Main (string[] args)          {              student stu = new student ();              int Chinese = stu. Chinese;     Error, inaccessible (private)                           int 中文版 = stu. 中文版;   can access (public)                int total = Stu.total ();  Cannot access private method          }}}  

Because the variable Chinese, the Math method total has private access restrictions in the student class, it cannot be accessed through object Stu

protected modifier

The Protected access modifier allows subclasses to access the member variables and member functions of its base class. This helps to implement inheritance. (Object access not allowed, method access in class allowed, subclass access allowed)

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;    Namespace Test  {      class student      {          ///define protected type protection          protected int chinese=80;          protected int math=67;          protected int english=45;            protected int Total ()          {              int sum = 0;              sum = Chinese + Math + 中文版;              return sum;          }      }      Class Teacher:student  //teacher inherits student class      {          static void Main (string[] args)          {              teacher Teac = new Teacher ();   Create subclass Teacher Object              //All successful access              int chinese = teac. Chinese;                               int 中文版 = Teac. 中文版;                  int total = Teac.total ();}}  

Internal modifier

The Internal access modifier allows a class to expose its member variables and member methods to other methods and objects in the current assembly (the current project). In other words, any member with the internal access modifier can be defined to be accessed by any class or method within the assembly (project) defined by that member.

To learn the internal modifier, we first have to learn to create multiple projects and engineering and project reference methods using Vs2010:

Create a project file first: named Test_internal

After clicking OK, locate the solution Manager:


Right-click Solution "Test_internal" (1 items)---> Add---> New project---->visual C #---> console; In the Name field we named Class_internal OK; so we created 2 items (assemblies)


In fact, the name we entered above is the name of the namespace we define, open code class_internal namespace is namespace class_internal, Test_internal namespace is namespace Test_ Internal, we use the using namespace to reference the content of another project in a project, but before we do, we have to add the referenced project path in the references list:

Right-click the reference---> Add Reference---> Project. Find the project name to refer to in the list of project names here we choose Class_internal Click OK, the reference list will be more class_internal reference success

We open the Program.cs in class_internal to edit the following code

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;    Namespace Class_internal  {public      Class student      {  //define 2 internal access types with a public access type          internal int chinese=80;          internal int math=70;          public int english=56;        Defines a internal access type method          internal int total ()          {              int sum = 0;              sum = Chinese + Math + 中文版;              return sum;          }          static void Main (string[] args)          {                     }      }       }

Then edit the following code in Test_internal:

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;  Using Class_internal;  Reference namespace    namespace test_internal  {class program      {          static void Main (string[] args)          {              Student stu = new student ();  Instantiate an student type              int chinese = stu. Chinese;   Error, internal protection type cannot access              int Math = stu in this project. Math;  Error, ibid.              int 中文版 = stu. 中文版;  Successful access to public protection type}}}  

We use internal and public access types in class_internal, and only public access types can be accessed in another project test_internal. This is internal.

protected internal modifier

The Protected Internal access modifier allows a class to hide its member variables and member functions from class objects and functions other than subclasses of the same application (project). (not quite) in other words, having the properties of both protected and internal, protected access is restricted to subclasses, can be accessed through inheritance in another assembly (project), internal is restricting access to other items, two limit overlays, The protected type cannot be accessed through an inherited subclass in another project.

The above is the C # learning diary----The contents of the package and access modifiers, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.