4. Class and encapsulation, 4. Class Encapsulation

Source: Internet
Author: User

4. Class and encapsulation, 4. Class Encapsulation
For more information, see Andrew Troelsen's C # And. NET4 advanced programming. This section describes the following:

1. Construct a class that supports defining any number of constructors.

2. Basic knowledge of classes and allocation objects

3. Encapsulation

4. Define class attributes and the functions of static members, object initialization syntax, read-only fields, always bright, and segmented classes

C # class type. the most basic programming structure of the net platform is the class type. Formally speaking, the class is composed of field data (member variables) and the custom types of the members (constructors, attributes, methods, events, etc.) that operate on the data. In general, the field data is used to indicate the 'status' (object) of the class instance ). C # the strength of this object-based language is that by combining data and related functions in class definitions, we can design software based on real-life entities. (Surface object) class Definition: // the keyword is class, and the class name is the state of Car class Car {// Car public string petName; public int currSpeed; // Car function public void PrintState () {Console. writeLine ("{0} is going {1} MPH. ", petName, currSpeed);} public void SpeedUp (int delta) {currSpeed + = delta ;}} indicates that although two common fields are used to represent the 'status' of the class ', however, fields of a class are rarely defined as public. To protect the integrity of state data, we generally define fields as private and provide controlled access to data through type attributes. If the member variable is defined above, the behavior of the member is described, for example, a SpeedUp () method and a PrintState () method in the above class. write the following code in the Program class: static void Main (string [] args) {Console. writeLine ("***** Fun with class types *****"); Car myCar = new Car (); myCar. petName = "Henry"; myCar. currSpeed = 10; for (int I = 0; I <= 10; I ++) {myCar. speedUp (5); myCar. printState ();} Console. readLine ();} when we run the program, we can see the status data output by the class method. New Keyword: the object must be allocated to the memory with the new keyword. The new keyword is mainly used to pay the reference to the object. The reference is assigned to the object only after new, which directs to the effective class instance in the village. If you want to assign values to the object field data before using the object, you can use the constructor. Constructor is a special method of a class. It is indirectly called when an object is created using the new keyword. Unlike the 'normal' method, the constructor never returns a value, and its name is always the same as the name of the class to be constructed. 1. default constructor: Each C # class provides built-in default constructor, which can be redefined as needed. According to the definition, the default constructor does not accept any parameters. Update the following method in the above class: public Car () {petName = "GoodGirl"; currSpeed = 10;} after we create an object, directly calling the PrintState method will print out GoodGirl is going 10 MPH.2. custom constructor: apart from the default constructor, we can also customize different constructor. The difference between constructors is the number and type of constructor parameters. If we define a method with the same name but the number and type of parameters are different, it is to overload the method. Therefore, our custom constructor is equivalent to a method overload. For example, in addition to the above constructor, we can also construct the following: public Car (string p) {petName = p;} 3. next, let's talk about the default constructor: If a custom constructor is defined, the default constructor will be automatically removed from the class and will no longer be valid. Therefore, if you want the object user to use the default constructor and user-defined constructor to create a type instance, you must re-define the default constructor. Create a class as follows: class Motorcycle {public int intensity; public void PopAWheely () {for (int I = 0; I <= intensity; I ++) {Console. writeLine ("aaaa hhhhh! ") ;}}// Display the default constructor public Motorcycle () {}// custom constructor public Motorcycle (int intensity) {this. intensity = intensity;} role of this keyword C # supports this keyword to provide access to the current class instance. The possible purpose of this keyword is to solve the Scope Ambiguity generated when the name of the input parameter and the name of the type data field are the same. As shown in the preceding example, in the last constructor, this. intensity refers to the field defined in the class, and the intensity assigned to it is the parameter of the constructor. Note: If this keyword is implemented in the implementation of static members, a compilation error occurs. We know that static members act at the class (rather than the object) level, so there is no current object at the class level (that is, there is no this ). 1. use this to call a series Constructor (simplified programming): Another use of this keyword is to design a class using a technology called constructor chain, this design mode is useful when the class defines multiple constructors. If multiple constructors have the same processing logic but different parameters, code redundancy is easily generated. At this time, this keyword concatenation is very useful. we can construct a constructor that accepts the maximum number of parameters as the Zhu constructor and implement the necessary verification logic. // Default constructor public Motorcycle () {}// constructor chain public Motorcycle (int intensity): this (intensity, "") {} public Motorcycle (int intensity, string name) {if (intensity> 10) {intensity = 10;} driverIntensity = intensity; driverName = name;} 2. constructor process: After the constructor Passes parameters to the specified Primary Constructor (and the constructor processes data, the constructor called by the caller will execute all remaining code statements. (That is, all the processes in the constructor are completed ). The logical process of the constructor is as follows: 3. optional parameters: previously mentioned. Optional parameters allow us to provide default values for input parameters. If the caller wants to use these default values instead of using custom data, they do not have to be set separately. Although the optional/named parameters simplify the way to define a function set for a given class, remember that this syntax can only be compiled in C #2010 and can only be in. run net4 ). Optional parameter constructor in the following format: public Motorcycle (int intensity = 0, string name = "") {// processing logic} static Keyword: C # class (or structure) you can use the static keyword to define many static members. In this case, these members can only be called directly from the class level rather than object reference. For example, the WriteLine () method in the Console. In short, static methods (class designers) are considered to be very common items and do not need to call Members to create type instances. 1. define static methods: public static string A () {// processing logic}; static members can only operate static data or call static methods of the class, if you normally use non-static class data in static members or call non-static class methods, you will receive a compilation error. 2. define static data: public static double currentNum = 0.04; unlike non-static data, each object maintains an independent copy of the field. The static field is only allocated once in the memory, after that, all types of object operations will be the same value. Therefore, remember that static data fields are shared by all objects. Therefore, if you want to define a data point that all objects can share, you can use static members. 3. define a static constructor: A constructor is used to set the data value of an object when an object is created. Therefore, if a value is assigned to a static data member in an instance-level constructor, you will be surprised to find that the value is reset every time you create an object. This method seems to be against our design class principles, but it will be very useful if you need to obtain the value of static data at runtime. In short, a static constructor is a special constructor and is very suitable for initializing static data values unknown during compilation. Static constructor features: 4. Defining static classes: If you apply the static keyword directly at the class level, you cannot create it using the new keyword and can only contain members or fields marked by the static keyword. Note: A class or structure that only contains static functions is usually referred to as a tool class. It is a good practice to define a class as a static class when designing a tool class. The pillar of OOP is the principle of object-oriented language. Encapsulation, inheritance, and polymorphism. 1. encapsulation: encapsulation is a language capability that hides implementation details that are not understood by the object user. The concept closely related to the encapsulation programming logic is data protection. Ideally, the object state data should be specified using the private keyword. In this way, the external world cannot directly change or obtain the underlying value, which can prevent data points from being damaged. 2. The role of inheritance: Inheritance refers to the ability to create custom language based on existing class definitions. Essentially, through inheritance, child classes can inherit the core functions of the base class (parent class) and expand the behavior of the base class. Another form of code reuse in oop CNOOC: Include/delegate model (has-a relationship ). This type of reuse is not used to establish the parent class/subclass relationship. It means that a class can define the member variables of another class and indirectly expose its functions to the object users. 3. The role of polymorphism: Polymorphism represents the ability of a language to process objects in the same way. To be precise, this object-oriented language principle allows the base class to define a member set (multi-state interface) for all derived classes ). C # access modifiers C # include private, public, protected, internal, and protected internal. The following table describes the functions of the C # member type modifier and default modifier: private, protected, and protected internal access modifier can be applied to nested types. Nested types are directly declared in the class or structure scope. Non-nested classes can only be defined using public and internal modifiers. C # the core concept of encapsulation Service (the first pillar of OOP) encapsulation is that internal data of objects should not be directly accessed from object instances. If the caller wants to change the object state, use the access method (getter) and modification method (setter ). In C #, encapsulation is embodied at the syntax level through the private, public, protected, and internal keywords. Encapsulation provides a method to protect the integrity of state data. Compared with defining common fields, more private data fields should be defined. Such fields can be operated indirectly by the caller. There are two main ways to define private fields (Black Box programming): 1. Use the traditional access method and modification method to execute encapsulation: get method and set method. The set method can change the value of the current actual status data. Definition: class A {private string name; // get public string GetName () {return name;} // set public void SetName () {// processing logic} 2. use.. net attribute encapsulation: although the data of these fields can be encapsulated using the traditional method of obtaining and setting ,. the net Language still advocates the use of attributes to forcibly encapsulate State data. C # attributes consist of get scopes (access methods) and set scopes (modification methods) defined in the attribute scopes. attributes specify the data types they encapsulate through the return values. The value mark in set is used to indicate the value passed in when the caller sets the attribute. Private int id; public int ID {get {return id;} set {id = value;} attribute has the following benefits: it makes the type easy to operate, because attributes can be used in combination with the C # Internal operator. 3. Use the class attributes, especially the set part of the attributes, to package the class business rules. Using attributes directly in a class is better, which will reduce repeated checks or judgments. 4. Internal representation of attributes: Many programmers often use get _ and set _ prefixes to name traditional access methods and modification methods. This naming convention is fine, but at the bottom layer, the C # Attribute uses the same prefix as the C # attribute, which can be clearly seen in the pencil code. You can use ildasm.exe to open the exe program for viewing. Description: When encapsulating field data ,.. net basic library always uses the type attribute instead of the traditional access method and modification method. Therefore, if you want to create. net platform, do not define traditional access methods and modification methods. To avoid compilation errors because the method names defined in the class are the same. 5. Control the visibility level of get/set statements for properties: in some cases, it is helpful to specify a unique accessible level for obtaining and setting the logic. Therefore, we can use the accessible keywords as the prefix of the appropriate get or set keywords: public string A {get {return a;} protected set {a = value ;}} 6. read-only and write-only attributes: When encapsulating data, you may want to configure a read-only attribute. Therefore, you can ignore the set block. If you want to write only properties, the get block is ignored. In this way, if a read-only attribute is assigned a value, a compilation error occurs. 7. Static attributes: C # also supports static attributes, which must be operated on static data. C # you like to use attributes to encapsulate data. The advantage of attributes is that an object user can use only one name item to operate internal data. The automatic attribute public int A {get; set;} does not allow the creation of read-only and write-only attributes, for example, public int A {get;} may generate A compilation error. 1. Interaction with automatic attributes: Since the compiler defines private returned fields during compilation, classes that define automatic attributes usually need to use the attribute syntax to obtain and set actual values. Attribute Syntax:. B = "aa"; 2. about automatic attributes and default values: You can directly use the automatic attributes that encapsulate numbers or boolean data in the code library, because hidden return fields will set a security default value that can be used directly. However, if the automatic property encapsulates another class variable, the default value of the hidden private reference type is also set to null. Public int A {get; set;} // The Hidden int returned field is set to 0 public Car B {get; set;} // The Hidden Car returned field is set to null; because private returned fields are created at compilation, you cannot use the C # field initialization syntax to directly assign reference types with the new Keyword. This must be executed within the class constructor, to ensure that the object is born in a safe way. Class Car {public int A {get; set;} public Car () {A = 1 ;}} object initializer syntax to simplify the process of creating an object, C # provides the object initializer syntax, which consists of a list of specified values separated by commas (,): Car = new car () {petName = "abc ";} the object initialization syntax is simply a shorthand form for creating class variables using the default constructor and setting the State data of each attribute. Constant data const int a = 100; C # defines a constant using the const keyword (it has never changed since the initial value is assigned ). The constant fields of the class are implicitly static. However, we can define and access local constants in type members. Note: when defining a constant, you must specify its initial value. Otherwise, a compilation error occurs. 1. Read-Only field: public readonly double pi; the constructor {pi = 3.14} of public Car () // car is similar to a constant. The read-only field cannot be changed after the initial value is assigned. However, unlike constants, the value assigned to a read-only field can be determined at runtime. Therefore, it is valid to assign values in the constructor scope (not elsewhere ). 2. Static read-only fields: Unlike constants, read-only fields are not implicitly static. Therefore, to make pi public at the class level, you must use the static Keyword: add the static keyword above, and the constructor must also be static. In this way, the value of the static read-only field is not known until running. The partial type can use the partial keyword to create a partial class. Use the segmented class to transfer the constructor and field data to a new class file, which can avoid too much code in a single cs file. The entire concept of the Division class is implemented during design. After the application is compiled, only the unique class exists in the program set. The unique requirement for defining a division class is that the type name must be the same and must be defined in the same. net namespace. If you use winform or wpf, you will find that many hidden code files use this method of the partial class. Partial class A {} Summary This section mainly introduces the role of the class type, as well as its constructor, its members, and various representations and definitions of member variables. In addition, details of encapsulation are also exposed. Encapsulate this part. We learned the access modifier of C #, the type attribute, the object initialization syntax, and the role of the Division class. The next section will learn inheritance and Polymorphism to build a group of related classes.

 

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.