C # Object-oriented three major features

Source: Internet
Author: User

C # Object-oriented three major features

The three basic characteristics of object-oriented are encapsulation, inheritance, polymorphism.

Packaging:
Hide the specific implementation of internal features, and only retain and externally communicate data for the pretext. It's like a TV, with a shell that encapsulates internal components and control circuitry, and only provides a button or remote interface for people to use.
encapsulation can hide implementation details so that the code module of the.
To encapsulate into a class or structure:
Classes and structs are actually templates that create objects, each of which contains data and provides methods for processing and accessing the data.
The (1) class defines what data and functionality each class object (instance) can contain. For example, if a class represents a customer, we can define the field customerid,name and address to contain the customer's information, and also define the functionality to process the data stored in those fields. Then, as we often write, new instantiates the object to represent a customer and sets the fields for that instance to use its functionality.
The way structures are stored in memory (classes are reference types stored on the heap (heap), and structs are value types stored on stacks), access methods, and some characteristics (such as structs that do not support inheritance) are different from classes. Using structs for smaller data types can improve performance. But in syntax, structs and classes are very similar, the main difference is the use of the keyword struct instead of class to declare the structure, in C #, the structure can be seen as a shrinking class.

(2) Class members
The data and functions in the class are called members of the class. Class members can be divided into data members and function members.
Data members contain the data of the class-Fields, constants, and events.
Function members provide some functionality for manipulating data in classes, including methods, constructors, properties and finalizers (finalizer), operators, and indexers.

(3) Special classes
In encapsulating the class, we may construct some "special" classes (such as static classes, abstract classes, etc.) as they are actually needed, and briefly describe the common special classes.
<1>, Static class
If a class contains only static methods and properties, the class can be static. A static class is functionally the same as a class created using a private static constructor. You cannot create a case for a static class. With the static keyword, the compiler can check if an instance member is added to the class later, and if so, a compilation error occurs.


<2>, Sealing type
C # allows classes and methods to be declared as sealed. For a class, this means that the class cannot be inherited, which means that the method cannot be overridden for the method. However, there is no point in using sealed on a method unless the method itself is an overriding form of another method on a base class. If you define a new method, but don't want others to rewrite it, first don't declare it as virtual. But if you are overriding a base class method, the sealed keyword provides a way to ensure that the rewrite code provided for the method is the final code, and that no one else can rewrite it.


<3>, abstract class
C # allows classes and methods to be declared abstract, abstract classes cannot be instantiated, and abstract functions do not execute code and must be overridden in non-abstract derived classes.


<4>, part of the class
The partial keyword allows you to place classes, structs, or interfaces in multiple files. In general, a class is stored in a single file. Sometimes, however, multiple developers need access to a class, or some type of code generator generates a part of a class, so it is useful to put a class in multiple files.

<5>, Object class
As we all know,. NET classes derive from System.Object. The method of this class is a method implemented by all. NET classes.

Method access Modifier effect
String ToString () public virtual returns the strings representation of an object
int GetHashCode () public virtual is used when implementing a dictionary (hash table)
BOOL Equals (object obj) public virtual compares an instance of an object to an equality
BOOL Equals (Object Obja,object objb) public static compares an instance of an object by equality
BOOL ReferenceEquals (Object Obja,object objb) public static compares two references to the same object
Type GetType () public returns details about the object type
Object MemberwiseClone () protected (cannot be overridden) for shallow copying of objects
void Finalize () protected. NET version of the virtual destructor

(2) structure (struct)
In many ways, the structure in C # can be seen as a shrinking class. It is basically the same as the class, but it is better suited to the occasion of combining some data together. Here's how it differs from the class:


<1>, structure is value type
A struct is a value type that is stored on the stack or stored as inline (if it is part of another object and is saved in the heap), with a lifetime limit of the same as a simple data type.
Note: Because structs are value types, the new operator and the class and other reference types work differently. The new structure does not allocate memory in the heap, but instead invokes the appropriate constructor, initializing all fields based on the parameters passed to it.

<2> structures cannot be inherited
The structure is not designed for inheritance. Cannot inherit from a struct, the only exception is that structs derive from class System.Object. Therefore, the structure can also access the System.Object method. The inheritance chain for structs is this: each structure derives from System.valuetype,system.valuetype derived from System.Object. System.ValueType does not add any new members to System.Object, but it provides some execution code that is more appropriate for the structure.
Note : structs can implement interfaces . That is, structs do not support implementation inheritance, but interface inheritance is supported.
A, structs are always derived from System.ValueType, and they can also be derived from any number of interfaces.
B, classes can derive from another class that the user chooses, and they can also derive from any number of interfaces.

<3> structure Constructors (structs cannot contain explicit parameterless constructors)
You define constructors for structs in the same way that you define constructors for a class, but you do not allow a parameterless constructor to be defined because it is hidden in the way that the. NET runtime is executed. That is, the. NET runtime cannot invoke a user-supplied custom parameterless constructor, so Ms prohibits the use of parameterless constructors within structs in C #.



Inheritance :
The greatest benefit of inheritance is the efficient reuse of code, as well as a more visually descriptive representation of the relationship of objects in the real world.

Use of inheritance:
When using object-oriented inheritance in the program, there are two kinds of cases, namely single inheritance and multiple inheritance.

1. Single inheritance

Single inheritance is generally used for inheritance between classes, and classes in C # only support single inheritance, with the "Subclass: base Class" format when implementing single inheritance.

2. Multiple inheritance

If you want to use multiple inheritance, you need to use an interface, because classes in C # only support single inheritance, whereas interfaces support multiple inheritance, and when multiple inheritance is implemented, multiple interfaces that inherit are separated by commas (,).

Principles of Succession:

1. In addition to the object class, each class has and has only one direct base class, and if the direct base class of the specified class is not displayed, its direct base class is implicitly set to object. The object class does not have any direct or indirect base classes,

It is therefore the ultimate base class.

2. Regardless of the accessibility of a base class member, except constructors and destructors, members of all other base classes can be inherited by subclasses, however, some inherited members may be inaccessible in subclasses, for example, private members of a base class are inaccessible in subclasses, but If you pass the object of a subclass as a parameter into a method of the base class, you can access the private members of the base class through the object of the subclass or subclass, within the code of the base class.

3. Subclasses can extend its direct base class.

4. Inheritance is transitive, such as Class C inherits from Class B, and Class B inherits from Class A, then Class C inherits both the members of Class B and the members of Class A.

5. Classes cannot loop inheritance, such as Class A inherits from Class B, and Class B inherits from Class C, then Class C cannot inherit class A because there is a circular relationship between them.

6. The direct base class of a class must be at least as accessible as the class itself, for example, if a public class is derived from the private class, it will result in a compile-time error.

7. In a subclass, a new member with the same name or signature can be declared to hide a member inherited from a base class, but hiding the inherited member does not remove the member, but only makes the hidden member inaccessible directly in the subclass.

8. A virtual method can be declared in a class, and subclasses can override the implementation of these virtual methods

Only single inheritance of classes is supported in 9.c#, but multiple inheritance of interfaces is supported.

10. An instance of a class contains a collection of all the instance fields declared in the class and all its base classes, and there is an implicit conversion from the subclass to any of its base classes, so that an instance of the subclass can be treated as a reference to an instance of any of its base classes.

To extend the implementation of the interface:

The implementation of an interface is implemented through class inheritance, although a class can inherit only one base class, but may inherit any number of interfaces. When declaring a class that implements an interface, you need to include the name of the interface that the class implements in the list of base classes.

The syntax format for implementing inheritance in C # is as follows:

Class Derivedclass:baseclass {}

Description

When inheriting a class, you must use a colon (:) between the subclass and the base class, and, if you inherit multiple interfaces, separate the inherited interfaces with commas (,).

To extend an explicit interface member implementation

If a class implements two interfaces, and the two interfaces contain members with the same signature, then implementing that member in the class will result in two interfaces using that member as their implementation, however, if two interface members implement different functions, This may result in an incorrect implementation of one of the interfaces, or an incorrect implementation of the two interfaces, when an interface member can be implemented explicitly, creating a class member that is called only through that interface and is specific to that interface. An explicit interface member implementation is implemented by using the interface name and a period to name the class member.

Extending "interface Features"

1. An interface is similar to an abstract base class: Any non-abstract type that inherits an interface must implement all members of the interface;

2. The interface cannot be instantiated directly;

3. An interface can contain events, indexers, methods, and properties;

4. The interface does not contain the implementation of the method;

5. Classes and structs can inherit from multiple interfaces;

6. The interface itself can inherit from multiple interfaces.

Description

An interface separates a service's protocol from its implementation, which is the basis for component programming, in which the interface is the only way for components to advertise their functionality out of the box.

Extending the "declaration interface"

C # uses the interface keyword to declare an interface with the following syntax:

Modifier Interface Interface Name: List of inherited interfaces

{

interface content;

}

Description

(1) When declaring an interface, it usually begins with the capital letter "I";

(2) When declaring an interface, except for the interface keyword and the interface name, the other is optional;

(3) interfaces can be declared using modifiers such as new, public, protected, internal, and private, but interface members must be common.


Polymorphic:
That is, the same action with different objects produces different specific behavior. For example, driving is an action, but driving in the car and the aircraft, there are different specific driving operation and process. Its benefits are the specification and simplification of the interface design. For example, the switch mark symbols you see are basically the same, so that you can easily identify and understand them. In simple terms ( programming with a base class or interface variable)

In polymorphic programming, a base class is generally an abstract class that has one or more abstract methods that each subclass can override as needed. or using interfaces, each interface prescribes one or more abstract methods, and the classes that implement the interfaces implement these methods as needed.

Therefore, the implementation of polymorphism is divided into two basic categories: inherited polymorphism and interface polymorphism.

Inheritance polymorphism

The zoo keeper is supposed to feed his dead lions, monkeys and pigeons every day.

First, set up three classes representing three animals, respectively.

The breeder is represented by the feeder class. As three animals eat animals, the feeder class must have three public ways to feed the animals:

The process is as follows:

If the leader has to hand over the panda to his management, it is our procedure to give the feeder class A way to add: Feedpanda ();

In case Xiao Li later does not care about the monkeys, but also remove the Feedpigeon () method from the feeder class.

So this kind of programming is obviously unreasonable.

We can solve this problem by applying polymorphic methods.

First, because they are all animals, it is possible to create a animal abstract base class.

Because different animals eat different foods, an abstract method is defined in the Animal class: Eat (), with subclasses responsible for implementation.

Now, you can combine the three feeding methods of the feeder class into one feedanimal:

Feeder Class Code:

Feeding process:

We modify the definition of the feeder class, add a new Method Feedanimals (), the new method of the remote function is to feed a group of animals, accept the array of animal:

The process is as follows:

The elements of the array ans in the code are animal, so that you can deposit any one of the animal's subclasses in it. An array with this attribute becomes a " polymorphic array ".

The application of polymorphism in programming can be simplified into two sentences:

Application inheritance implements unified management of objects.

The application interface defines the behavior characteristics of an object.

Benefits of using polymorphism:

When you want to modify the program and expand the system, you need to modify less places, less impact on other parts of the code.

C # Object-oriented three major features

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.