The basic concept of object-oriented

Source: Internet
Author: User

OOP Technology manages complex things according to the characteristics of the real world, abstracts them into objects, has its own state and behavior, and accomplishes certain tasks by reacting to the message. This programming method provides a very powerful variety, greatly increases the reuse of code, increases the speed of program development, and reduces the maintenance burden, the independent special-purpose program code is packaged, and the modification of some program code does not affect the other parts of the program.

1. Object

What is an object? In fact, the real world is composed of a variety of objects, such as people, cars, animals, plants and so on. Complex objects can be made up of simple objects. Objects have their own properties, such as shape, color, weight, and so on, the external world shows their own behavior, such as people can walk, talk, sing, car can start, accelerate, slow down, brake, stop and so on.

In OOP, an object is a collection of variables and related methods. Where the variable indicates the object's properties, the method indicates the behavior of the object. A variable of an object forms the core of the object, and the method that surrounds it separates the object from other objects. For example: We can abstract the car into an object, using a variable to represent its current state, such as speed, oil, model, location, etc., its behavior is the above mentioned acceleration, braking, shift and so on. When operating a car. Instead of thinking about the details of how the parts work inside the car, just use the appropriate method according to the car's possible behavior. In fact, object-oriented programming implements the encapsulation of objects so that we do not have to care about the details of how the object's behavior is implemented. Through the encapsulation of objects, modularization and information hiding are realized. Facilitates the portability and security of the program, while also facilitating the management of complex objects.

To put it simply, objects are very similar to the type of structure discussed earlier in this book. A slightly complex object may contain no data, but only functions, representing a process.

2. Class

In the study of objects, the main consideration is the properties and behavior of objects, and some different objects will present the same or similar properties and behaviors, such as cars, trucks, vans. Attributes and behaviors are usually grouped into one category or similar objects. A class can be viewed as an abstraction of an object, representing the common properties and behavior of such an object. The typical class is "human", which indicates the common nature of man. For example, we can define a car class to describe the commonality of all cars. By class definition people can implement code reuse. Instead of describing each object (such as a car), we create an object of that class by creating an instance of the class, such as a car class, which greatly increases the design of the software.

A class is an abstract description of a set of objects that have the same characteristics, all of which are instances of this class. In C #, a class is a data type, and an object is a variable of that type, and the variable name is the name of a specific object.

3. Properties and Fields

The data contained in an object can be accessed through properties and fields. Object data can distinguish between different objects, because different objects of the same class may store different values in properties and fields. The non-data contained in the object is collectively known as the state of the object.

Suppose an object class represents a cup of coffee, called Cupofcoffee. When instantiating this class (that is, the object that created the class), you must provide a state that is meaningful to the class. You can use properties and fields so that the code can set the coffee brand to use, whether the coffee is milk or sugar, and whether the coffee is soluble. The given coffee object has a specified state, such as "Columbian filter coffee with milk and sugars".

You can store information in fields and properties, as string variables, int variables, and so on. However, properties are different from fields, and properties cannot directly access data. In general, it is best to provide properties when accessing the state, rather than fields, because this gives you more control over the entire process, and the syntax for using them is the same.

Read-write access to a property can also be explicitly defined by the object. Some properties are read-only and can only view their values, not change the LUN (at least not directly). You can also have write-only properties that operate in a similar manner.

In addition to read-write access to properties, you can also specify a different access License for fields and properties, which determines what code can access these members, whether they are available for all code (public), or only for code (private) in a class, or for more complex patterns. The common scenario is to set the fields to private and access them through public properties.

For example, a Cupofcoffee class, you can define 5 members: Type, Isinstant, Milk, Sugar, description, and so on.

4. Method

All the behavior of an object can be described in a method, in C #, a function in an object.

Methods are used to access the functionality of an object, with fields and properties-like: Methods that can be public or private, restricting access to external code as needed. They often use object state-access to private members. For example, the Cupofcoffee class defines a method Addsugar () to increase the number of sugar cubes property.

In fact, all things in C # are objects. The main () function in a console application is a method of the class. Each of the variable types described earlier is a class. Each command used earlier is a property or method. Period character "." Separates the object instance name from the property or method name.

5. The life cycle of an object

Each object is a well-defined life cycle, from the beginning of the use of the class definition until it is deleted. In the life cycle of an object, there are two important stages in addition to the normal state of "in use":

Construction phase-the period at which the object was initially instantiated. This initialization process is called the construction phase, which is done by the constructor.

destructor phase-When you delete an object, you often need to perform some cleanup work, such as freeing up memory and completing the destructor.

5.1 Constructors

All objects have a default construct, which has no parameters and has the same name as the class itself. A class definition can contain several constructors that have different signatures that code can use to instantiate objects. Constructors with parameters are typically used to provide initial values for the data stored in the object.

In C #, constructors are invoked with the new keyword. For example, you can instantiate a Cupofcoffee object in the following way:

Cupofcoffee Mycup = new Cupofcoffee ();

Objects can also be created with a non-default constructor. As with the default constructors, non-default constructors have the same name as classes, but they also have parameters, such as:

Cupofcoffee Mycup = new Cupofcoffee ("Blue Mountain");

constructors, like fields, properties, and methods, can be public or private. Code outside the class cannot instantiate an object using a private constructor, but must use a public constructor. -Some classes do not have public constructors, and it is impossible for external code to instantiate them.

5.2 Destructors

Destructors are used to clean up objects. In general, you do not need to provide the code for the Deconstruction method, but instead the default destructor performs the operation. However, if you need to do some important things before you delete an object instance, you should provide a specific destructor.

6. Static members

Members such as properties, methods, and fields are unique to object instances where changing one instance of an object does not affect those members in other instances. In addition, there is a static member (also known as a shared member), such as a static method, a static property, or a static field. Static members can be shared between instances of a class, so they can be thought of as global objects of a class. Static and static fields can access data that is independent of any object instance, and static methods can perform commands that are related to an object type, but are not specific instances, and even objects that do not need to instantiate a type when using static members. For example, the Console.WriteLine () method used by the front draw is static.

Some of the techniques in OOP are discussed below, including: Abstraction and interface, inheritance, polymorphism, operator overloading, and so on.

1. Abstraction and interface

Abstract is to reduce the maintenance of the program version of the burden, so that the function of the provider and the users of the function separate, independent, each other unaffected.

In order to achieve abstraction, it is necessary to provide a common specification between the function provider and the user of the function, and the function provider and the user of the function should provide and use these functions according to this specification. This common specification is the interface, which defines the number of functions, function names, function parameters, parameter order, and so on. It is a programmatic construct that declares properties, fields, and methods. It is not implemented for these members and only provides definitions. The interface defines the criteria between the feature provider and the user of the feature, so as long as the interface is not changed, the feature provider can arbitrarily change the implemented program code without affecting the consumer.

Once an interface is defined, it can be implemented in a class. In this way, the class can support all the components and members specified by the interface. Note that interfaces cannot be instantiated, and execution must be implemented in the class that implements the interface.

In the previous coffee example, you can put properties and methods for more general use such as Addsugar (), Milk,sugar and

The instant is combined into an interface called Ihotdrink (the name of the interface usually begins with the capital letter i). The interface can then be used on other objects, such as the Cupoftea class.

A class can support multiple interfaces, and multiple classes can also support the same interface.

2. Inherited

Inheritance is the most important feature of OOP. Any class can inherit from another class, which means that the class owns all the members of the class it inherits from. In 00P, a class that is inherited (also called a derivation) is called a parent class (also known as a base class). Note Objects in C # can only derive from one base class.

Buses, taxis, vans, etc. are all cars, but they are different cars, in addition to the characteristics of cars, they also have their own features, such as different operating methods, different uses and so on. At this point we can implement them as subcategories of cars that inherit all the state and behavior of the parent class (car) while increasing their state and behavior. Through the parent class and the subclass, we implemented the class hierarchy, starting with the most general class, and then gradually specialization, defining a series of subclasses. At the same time, the reuse of code through inheritance also enables the complexity of the program to grow linearly rather than exponentially.

When you inherit a base class, the accessibility of the member becomes an important issue. A derived class cannot access a private member of a base class, but can access its public members. However, both the derived class and the external code can access the public members. This means that only these two accessibility can be used to allow a member to be accessed by both the base class and the derived class, but also by external code. To solve this problem, C # provides a third accessibility: protected, only derived classes can access protected members.

In addition to the protection level of a member, we can define its inheritance behavior for members. A member of a base class can be virtual, that is, a member can be overridden by a class that inherits it. A derived class can provide additional execution code for a member. This execution code does not delete the original code, and it can still access the original code in the class, but the external code cannot access them. If no other execution is provided, the external code accesses the execution code of the members in the base class. A virtual member cannot be a private member.

A base class can also be defined as an abstract class. Abstract classes cannot be instantiated directly. To use an abstract class, you must inherit the class, and abstract classes can have abstract members that do not have code implementations in the base class, so the execution code must be provided in the derived class.

Finally, the class can be sealed. Sealed classes cannot be used as base classes, so there are no derived classes.

In C #, all objects have a common base class object, as we mentioned in Chapter two.

3. Polymorphism

Polymorphism is another feature of object-oriented programming. In process-oriented program design, the main work is to write a process or function, these procedures and functions can not duplicate the same name. For example, in one application, you need to sort the numeric data, and you need to sort the character data, although the same sort method is used, but to define two different procedures (the names of the procedures are different).

In object-oriented programming, the "duplicate name" can be used to improve the abstraction and simplicity of the program. First of all, we understand the actual phenomenon, for example, "Start" is the operation of all means of transport, but different specific means of transport, its "start" operation of the specific implementation is different, such as the start of the car is "engine ignition-start engine", "start" the ship to "anchor", balloon airship "Start" is "inflatable --Cast off ". If you do not allow these features to use the same name, you must define "car start", "Ship Start", "Balloon airship start" methods. In this way, users need to remember a lot of names when using, the advantages of inheritance is gone. In order to solve this problem, a polymorphic mechanism is introduced in object-oriented program design.

Polymorphism refers to the coexistence of different methods with the same name in a program. Polymorphism is achieved mainly through subclasses overriding the parent class method. In this way, objects of a different kind can respond to a method of the same name to accomplish a particular function, but their specific implementation can vary. For example the same addition, adding two time together and adding two integers together must be completely different.

With method overrides, subclasses can re-implement some of the methods of the parent class so that they have their own characteristics. For example, in a car-class acceleration method, a subclass (such as a racing car) may have added some new parts to improve the acceleration performance, which can be overridden in a racing class to speed up the parent class. Overrides a method that hides the parent class so that the subclass has its own concrete implementation, further demonstrating the specificity of the subclass compared to the parent class.

Polymorphism makes language flexible, abstract, and behavior-sharing advantages, which solves the problem of application function with the same name.

Note Not only classes that share the same parent class can take advantage of polymorphism. As long as the subclass and grandson classes are in the inheritance hierarchy

Have the same class, they can take advantage of polymorphism in the same way.

4. Overload

Method overloading is another way to implement polymorphism. With method overloading, a class can have multiple methods with the same name, and the different number of arguments passed to them determines which method to use. For example, for a drawing class, it has a draw () method for drawing or outputting text, and we can pass it to a string, a rectangle, a circle, and even the initial position of the drawing, the color of the graphic, and so on. For each implementation, only a new draw () method can be implemented without a new name, which greatly simplifies the implementation and invocation of the method, and programmers and users do not need to remember many of the method names, just pass in the corresponding parameters.

Because a class can contain instructions on how operators operate, you can use an operator with an object instantiated from a class. We write code for overloaded operators and use them as part of the class definition, which acts on this class. You can also overload operators to handle different classes in the same way, where one (or two) class definition contains code that achieves this purpose.

Note You can only overload an existing C # operator in this way, and you cannot create a new operator.

5. Messages and Events

Objects must interact with each other to implement complex behavior. For example, to speed up a car, you must send it a message telling it what to do (this is acceleration) and the parameters needed to implement the action (this is the speed required). A message contains three aspects: the recipient of the message, the method that the receiving object should take, and the parameters required by the method. Also, the object that receives the message may return some information to the object that sent the message after the corresponding method has been executed. In the above example, the car's instrument will appear to have reached the speed and so on.

In C #, message processing is called an event. objects can activate events as part of their processing. To do this, you need to add an event handler to your code, which is a special type of function that is called when an event occurs. You also need to configure this handler to listen for events of interest to us.

Events can be used to create event-driven applications that are a lot of applications. For example, many Windows-based applications rely entirely on events. Each button click or scroll bar drag operation is implemented through event handling, where events are triggered by the mouse or keyboard. Later in this chapter, you'll learn how events work.

The basic concept of object-oriented

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.