(c# Note) Object-oriented chapter

Source: Internet
Author: User

The three main features of object-oriented programming: encapsulation, inheritance, polymorphism.

First, the package
Encapsulation is the combination of data to form an object. After the class is encapsulated, it provides accessible properties and methods for external objects to access information about the object through these properties and methods.
Classes are tools that support object encapsulation, and objects are the basic units of encapsulation.

Benefits of Encapsulation:
1, good package can reduce the coupling.
2, the implementation within the class can be freely changed.
3, the class has a clear external interface.

Encapsulation is primarily controlled by access modifiers.
Here are five access modifiers, public,private,protected,internal,protected internal.

Public is the "common" meaning that if modified by the access modifier, it will be accessed anywhere.

Private is meant to be "privately", and is only accessible to the class in which it is modified by the access modifier.

Protected is meant to be "protected" and is only accessible to the class and its subclasses in which it is modified by the access modifier.

Internal is an "internal" meaning that is modified by the access modifier to be accessed only within the project in which it resides. Other items cannot be accessed.

Protected internal is "internally protected" and is modified by the access modifier to be accessed only within the class of the element and its subclasses in the project.

Private level: Private>protected internal>protected>internal>public

The default modifier for an enum type (enum) is public and cannot be decorated by other access modifiers.

The default modifier for a member of a field, property, method, and so on in a class is private and can be decorated with any other modifier.

The default modifier for the Class (class) is internal, which can be decorated with any other modifier.

The default modifier for Interface (interface) is public and cannot be decorated by other modifiers.

{About Interface}

//private interface Interface1错误在命名空间中定义的元素无法显式地声明为 private、protected 或 protected internal//internal interface Interface1 Internal虽然可以修饰接口,但是不建议去用internal。因为我们的接口是要对外通信的,使用public以便于其他项目能够重复利用此接口的代码publicinterface Internal1{//接口可以是方法、属性和事件,但是不能有任何成员变量,也不能在接口中实现接口成员。接口不能被实例化。接口的成员默认都是公共的,因此不允许成员加修饰符。//void Interface() { }错误“面向对象篇.Internal1.Interface()”: 接口成员不能有定义void Interface();}

The default modifier for struct (struct) is private and can be public,internal,private decorated.

 Public classclassfather{Private structDate { Public intDay Public intMonth Public intyear;};//struct member defaults to private, with an access modifier before the struct's inner element when declaring the struct//This is a private field that indicates that the field can be modified by privatePrivate intFieldprivate;//This is a public property that indicates that the property can be decorated Public intfieldprivate{//This is the Get method of the property, that is, the value method, which takes the value of the private field fieldprivate. Get{returnFieldprivate;}//This is the set method of the property, which is the assignment method, which assigns the value of the property to the private field. Set{fieldprivate =value;}}//This is a public field that indicates that the field can be decorated Public intFieldpublic;//This is a public auto attribute Public intFieldpublic {Get;Set; }//This is an internal fieldInternal intfieldinternal;//This is a protected fieldprotected intfieldprotected;//This is an internally protected fieldprotected Internal intfieldprotectedinternal;//This is a private automatic attributePrivate intFieldprivate_ {Get;Set; }Private void methodprivate() {Console.WriteLine ("This is a private method");} Public void Methodpublic() {Date D;//Same as class, but can not use the New keywordD.month = D.year = D.day =0; Console.WriteLine ("This is a public method");}protected void methodprotected() {Console.WriteLine ("This is a protected method");}Internal void methodinternal() {Console.WriteLine ("This is an internal method.");}protected Internal void methodprotectedinternal() {Console.WriteLine ("This is an internally protected method");} Public Classfather(intField1,intField2,intField3,intField4,intFIELD5)//pass a value to the field through the constructor function { This. fieldprivate = field1; This. fieldpublic = Field2; This. fieldprotected = field3; This. fieldinternal = Field4; This. fieldprotectedinternal = Field5;//Use the This keyword to call member variables in this class}//Other modifiers do not give an example, you can try it yourself. }class program{Static voidMain (string[] args) {//Instantiate Classfather objectClassfather CF =NewClassfather ();//cf.fieldprivate = 0; Error "Object oriented chapter. Classfather.fieldprivate "is inaccessible because it is protected by the level limit this field can only be accessed and assigned in the class where life is locatedCf.fieldpublic =0;//This field is public decorated, so it can be accessed and assigned anywhere. Cf.fieldinternal =0;//This field is internal decorated, so it can be accessed and assigned value. //cf.fieldprotected = 0; Error "Object oriented chapter. Classfather.fieldprotected "is inaccessible because it is protected by a level that the field is protected decorated, so it can only be accessed and assigned in the class and its subclasses .//cf.fieldprotectedinternal=0; Error "Object-oriented chapter. Classfather.fieldprotectedinternal "is inaccessible because it is protected by a level that the field is protected internal decorated, so it can only be accessed and assigned in subclasses of the class and its same project ./************* method and field ***************///cf.methodprivate (); Error "Object-oriented chapter. Classfather.methodprivate "inaccessible because it is protected by a level limitCf.methodpublic ();//This method is modified by public, so it can be accessed and invoked anywhere. //cf.methodprotected (); Error "Object-oriented chapter. Classfather.methodprotected "inaccessible because it is protected by a level limitCf.methodinternal ();//This method is modified by internal, as long as it can be accessed and invoked within the project//cf.methodprotectedinternal (); Error "Object-oriented chapter. Classfather.methodprotectedinternal "inaccessible because it is protected by a level limit}}

The output is:
This is a public method
This is an internal method

Reasonable use of access modifiers enables the data in the project to be effectively protected. Make the code as modular as possible for maintenance and debugging.

Ii. inheritance
Inheritance means that a class can get all the members in that class except constructors and destructors in a way that inherits from a class. The inherited class is called the base class (or parent Class), and the inherited class is called a derived class (or subclass).

The essence of inheritance is code reuse. Subclasses have their own attributes on the basis of inheriting the existing properties and methods of the parent class.

Inheritance is commonly used to extract the same attributes, put in the parent class, and play a role in reducing the duplication of code.

If the child class inherits from the parent class. First, the subclass has the parent class non-private properties and functions; second, subclasses have their own properties and functions, that is, subclasses can extend the properties and functions that the parent class does not have, and thirdly, subclasses can implement the functions of the parent class in their own way (method overrides).

A subclass that can inherit from a parent class has methods, fields, properties, events, index indicators, but can only be called for construction methods that cannot be inherited. You can use the Base keyword for members that call the parent class.

If you do not use inheritance, if you want to modify the functionality, then you have to modify in all the repeated methods, the more code, the more likely the error, and the advantage of inheritance is that all subclasses of the public part of the parent class, so that the code is shared, which avoids duplication, in addition, Inheritance can make it easier to modify or extend inherited implementations.

Inheritance is also flawed, as the parent class changes, and the subclass has to change. Inheritance is a strongly coupled relationship between classes and classes.

//继承ClassFather类{publicClassSon(intintintintintbase(field1, field2, field3, field4, field5){//使用base 关键字为父类的成员变量赋值}}

Three, polymorphic
Polymorphism means that the same message or action can have different interpretations of different objects, resulting in different execution results.
There are two kinds of polymorphism in object-oriented programming: Static polymorphism and dynamic polymorphism.

Polymorphic representations of different objects can perform the same actions, but they are executed through their own implementation code.
1. The subclass appears as the parent class.
2. Subclasses work in their own Way (code) to achieve.
3. When a subclass appears as a parent, the properties and methods that are unique to the subclass are not available.
When a method of an object is called directly in the same class, the static polymorphism is determined based on information such as the number of arguments passed, the type of the parameter, and the type of return value.
When you invoke a method of an object indirectly in a class hierarchy that has an inheritance relationship, the operation that calls through the base class is dynamic polymorphic.

Implementation of static polymorphism--overloading
Overloading refers to allowing multiple functions with the same name, which have different parameters, perhaps different parameters, or different types of parameters, perhaps different.

Class program{Static voidOverload ()//static method function name with static flag{Console.WriteLine ("This is an overloaded method, the return value is NULL, the parameter is null");}Static intOverload (int value)//Take int as an example, other types are the same as int{Console.WriteLine ("This is an overloaded method, the return value is int, the argument is int"+value);return value;}Static intOverload (intValue1.intvalue2) {Console.WriteLine ("This is an overloaded method with a return value of int and a parameter of Int,int"+ value1 + value2);returnvalue1;}Static voidMain (string[] args) {overload ();intValue1 = Overload (2);intvalue2 = Overload (3,4);//static polymorphic function overload call}}

Output Result:
This is an overloaded method, the return value is null, the argument is empty
This is an overloaded method with a return value of int and a parameter of int 2
This is an overloaded method with a return value of int and a parameter of Int,int 34

Two implementations of dynamic polymorphism: Abstract classes and Virtual methods
Abstract class: Defines an abstract class using the abstract keyword. Declare an abstract method (but not defined) in an abstract class using the abstract keyword. In an abstract class subclass, you must override this abstract method with the Override keyword to define the functionality you need in the method. Abstract classes cannot be instantiated. If the class contains an abstract method, the class must be defined as an abstract class.

Virtual method: Use the virtual keyword in the parent class to define a dummy method (you can define a function). In subclasses where you need to change the parent virtual method functionality, you can use the Override keyword to override the parent class's methods. In addition to the field cannot be virtual, other properties, events, indexers can make the virtual

AbstractClass Polymorphismfather//The abstract method in a class must be declared as an abstract class{ Public Virtual void polymorphismvirtual() {Console.WriteLine ("This is a parent-class virtual method");} Public Abstract void polymorphismabstsact();//abstract method only declares undefined}class Polymorphisma:polymorphismfather//Inherit abstract class Polymorphisfather{ Public Override void polymorphismvirtual() {Console.WriteLine ("This is the first subclass overriding a virtual method");} Public Override void polymorphismabstract() {Console.WriteLine ("This is the first subclass of overriding abstract methods");}} Class polymorphismb:polymorphismfather{ Public Override void polymorphismvirtual() {Console.WriteLine ("This is the second subclass overriding the virtual method");} Public Override void polymorphismabstract() {Console.WriteLine ("This is the second subclass of overriding abstract methods");}} Class program{Static voidMain (string[] args) {Polymorphismfather PfA =NewPolymorphisma ();//Convert parent class to sub-class object using the Richter conversion method///Call method, first check that the subclass does not have a corresponding method, no more checking to the parent class, and so on. Pfa.polymorphismvirtual ();//Call the subclass Polymorphisma to override the virtual methodPfa.polymorphismabstract ();//Call the subclass Polymorphisma Override abstract MethodPolymorphismfather PfB =NewPOLYMORPHISMB ();p fb.polymorphismvirtual ();p fb.polymorphismabstract ();}}

The output is:
This is the first subclass overriding a virtual method
This is the first subclass overriding an abstract method
This is the second subclass of overriding virtual methods
This is the second subclass of overriding abstract methods

Object-oriented thinking: All things in the world are objects

Resources:
Blog Park – "Object-oriented"-inverse mind
Http://www.cnblogs.com/kissdodog/archive/2013/03/24/2979650.html

C # program Design-Yang Luqing Shanghai Jiaotong University Press

I am freshman, recently studying C # programming. This is based on their own feelings summed up, if there are insufficient places to welcome you to help me to correct the point below. The first time I write a blog, hope to get everyone's encouragement.

(c# Note) Object-oriented chapter

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.