. NET basics 06: getting started with object-oriented,. net06

Source: Internet
Author: User

. NET basics 06: getting started with object-oriented,. net06

I. Preface

In the first part of this series of courses, we explain that in order to select C # as your first programming language:

• First, C # Is a very good object-oriented programming language;

Anyone interested in coding must have heard of the concept of "Object-Oriented Programming". C # was born for this, and it is naturally object-oriented. Therefore, since "object-oriented programming" is the mainstream in the IT field, we chose C # without moving away from the mainstream.

In this section, we will talk about what is object-oriented and the most important and important concept of object-oriented development.

 

Ii. What is object-oriented

"Object-Oriented" is a mainstream idea in software development. It has three main features: encapsulation, inheritance, and polymorphism. Many software development tutorials use the case of a cat and a dog for Object-Oriented purposes. In fact, "Object-Oriented" is a very understandable concept in a sense. We have already talked about the concept of "class" in the previous example. Now let's talk about abstract classes and interfaces. Of course, we do not plan to use the example of a cat or a dog (a cat or a dog is an animal, and animals have the habit of eating, drinking, and dropping ......, But a cat has a cat's meow, and a dog has a dog's bark ......), Here is a practical example. We only need to think about the concept and associate it with a cat and a dog.

The actual example is Stream, FileStream, and MemoryStream Of the. Net Framework basic class library (hereinafter referred to as FCL:

 

public abstract class Stream
{
    public abstract void Write(byte[] buffer, int offset, int count);
}

public class FileStream : Stream
{
    public override void Write(byte[] array, int offset, int count)
    {
    }
}

public class MemoryStream : Stream
{
    public override void Write(byte[] buffer, int offset, int count)
    {
    }

These three classes are responsible for reading and writing bytes. I only use one of them to Write.

(TIP: What is a byte ?, The data in the program will exist in byte format. As long as we know that the read and write content, such as string and integer, is included in the memory, to the file, the actual read and write is the byte)

1: What is encapsulation?

In a word: As shown above, code is classified into different classes, which is actually encapsulation.

2: What is inheritance?

As shown above, there is a parent class Stream, and there are two sub-classes called inheritance. If we want to talk about inheritance, we need to explain the access restrictions.

2.1 What is an access restriction?

In C #, it can be a type, such as a Stream class, or a member of the type, such as the Write method, to add an access restriction character. In the world of C #, we divide the visible scopes of type and type members into the following categories (Note: only the most common ones are described ):

A) visible throughout the application

Use public modifier.

B) visible in the current project

Use internal.

C) visible inside the current type

Use private. This modifier is mainly used to modify members of the type.

D) Visible only in the subclass

Use protected. This modifier is mainly used to modify members of the type.

It should be emphasized that the default access restricted character of the type is internal. If we do not add any modifier, the. NET compiler will default this type to internal. The access restricted character of a member of the type is private.

Now, let's stop and create some type and type members to understand the access restriction.

2.2 What is an abstract class?

How to create a class object? Use new as follows:

Stream stream = new Stream ();

However, you cannot execute this code, because Stream is an abstract class and it is modified in abstract. Since the abstract class is new, cannot it? So what does it mean?

A) First, it can define some abstract methods abstract method, which expresses this meaning: Hi, subclass, you must implement this method;

B) Secondly, the abstract class can have some common non-abstract methods. That is to say, we can put the same logic in some subclasses into this abstract method, in this way, you do not need to write the same code in different subclasses.

2.3 what is an interface?

If an abstract class has only abstract methods, but not conventional methods, we can consider abstracting it into interfaces ). An example of a simple interface is as follows:

Interface IDispose
{
Void Dispose ();
}

So when to use interfaces and abstract classes? This is a good question, but don't worry. As a beginner, it is difficult for us to grasp this standard. For now, we only need to directly. in the world of NET, classes, abstract classes, and interfaces can exist. Trying to understand them all in one breath is often a blessing.

3: What is polymorphism?

In a word, make the subclass have its own behavior, that is, polymorphism. Well, in fact, polymorphism can not be summarized in one sentence. Let's take a look at the specific meaning and implementation methods of polymorphism.

 

Iii. Meanings and implementation methods of Polymorphism

Note: The following content is taken from my book "high-quality code writing: 157 suggestions for improving C #". Note: To fully understand the meaning and implementation methods of polymorphism, you must write your own code to savor it. Please follow the example below to understand it.

Override and new make our type system show polymorphism due to inheritance. Polymorphism is one of the three important features of whether a language is "object-oriented language. Polymorphism requires that subclass has a method with the same name as the base class method, and override and new are used:

If the method in the subclass contains the new Keyword, the method is defined as a method independent of the base class.

If the method in the subclass contains the override keyword, The subclass object will call this method instead of the base class method.

These two definitions seem abstract. to deeply understand the differences between them, let's look at an inheritance system:

 

public class Shape
{
    public virtual void MethodVirtual()
    {
        Console.WriteLine("base MethodVirtual call");
    }

    public void Method()
    {
        Console.WriteLine("base Method call");
    }
}

class Circle : Shape
{
    public override void MethodVirtual()
    {
        Console.WriteLine("circle override MethodVirtual");
    }
}

class Rectangle : Shape
{
}

class Triangle : Shape
{
    public new void MethodVirtual()
    {
        Console.WriteLine("triangle new MethodVirtual");
    }

    public new void Method()
    {
        Console.WriteLine("triangle new Method");
    }

}

class Diamond : Shape
{
    public void MethodVirtual()
    {
        Console.WriteLine("Diamond default MethodVirtual");
    }

    public void Method()
    {
        Console.WriteLine("Diamond default Method");
    }
}

View the inheritance system above. The type Shape is the base class of all sub-classes.

The Circle class override the MethodVirtual of the parent class, so even if the subclass is transformed to Shape, the subclass method is called:

Shape s = new Circle ()

S. MethodVirtual ();

S. Method ();

Output:

Circle override MethodVirtual

Base Method call

Of course, the second method of Circle is well understood. Use the type of the subclass, and call all the methods of the subclass, as shown below:

Circle circle = new Circle ();

Circle. MethodVirtual ();

Circle. Method ();

The output is also:

Circle override MethodVirtual

Base Method call

Type Rectangle does not perform any processing on the base class. Therefore, no matter whether the subclass is transformed to Shape or not, the base class Shape method is called.

Type Triangle adds the virtual and non-virtual Methods of the base class Shape. So the first usage is:

Shape s = new Triangle ()

S. MethodVirtual ();

S. Method ();

Because the subclass has a new parent class method, the subclass method and the base class method have no relationship at all. As long as s is transformed to Sharp, the parent class method is called for s.

The second method is easy to understand. It calls subclass methods as follows:

Triangle triangel = new Triangle ();

Triangel. MethodVirtual ();

Triangel. Method ();

Output:

Triangle new MethodVirtual

Triangle new Method

The Diamond type contains two methods identical to the base class without any additional modifiers. This alert is reported in the editor. However, if you choose to ignore these warnings, the program can still run. Its first usage is:

Shape s = new Diamond ()

S. MethodVirtual ();

S. Method ();

The compiler will default the new effect, so the output is the same as the explicit new modifier.

Output:

Base MethodVirtual call

Base Method call

In the second method of Diamond, all the sub-classes are called, as shown below:

Diamond diamond = new Diamond ();

Diamond. MethodVirtual ();

Diamond. Method ();

Output:

Diamond default MethodVirtual

Diamond default Method

We will summarize all the above usage and provide a comprehensive example. Readers can carefully understand the output changes caused by each usage:

 

static void Main(string[] args)
{
    TestShape();
    TestDerive();
    TestDerive2();
}

private static void TestShape()
{
    Console.WriteLine("TestShape\tStart");
    List<Shape> shapes = new List<Shape>();
    shapes.Add(new Circle());
    shapes.Add(new Rectangle());
    shapes.Add(new Triangle());
    shapes.Add(new Diamond());
    foreach (Shape s in shapes)
    {
        s.MethodVirtual();
        s.Method();
    }

    Console.WriteLine("TestShape\tEnd\n");
}

private static void TestDerive()
{
    Console.WriteLine("TestDerive\tStart");
    Circle circle = new Circle();
    Rectangle rectangle = new Rectangle();
    Triangle triangel = new Triangle();
    Diamond diamond = new Diamond();
    circle.MethodVirtual();
    circle.Method();
    rectangle.MethodVirtual();
    rectangle.Method();
    triangel.MethodVirtual();
    triangel.Method();
    diamond.MethodVirtual();
    diamond.Method();
    Console.WriteLine("TestShape\tEnd\n");
}

private static void TestDerive2()
{
    Console.WriteLine("TestDerive2\tStart");
    Circle circle = new Circle();
    PrintShape(circle);
    Rectangle rectangle = new Rectangle();
    PrintShape(rectangle);
    Triangle triangel = new Triangle();
    PrintShape(triangel);
    Diamond diamond = new Diamond();
    PrintShape(diamond);
    Console.WriteLine("TestDerive2\tEnd\n");

}

static void PrintShape(Shape sharpe)
{
    sharpe.MethodVirtual();
    sharpe.Method();
}

Output:

TestShape Start

Circle override MethodVirtual

Base Method call

Base MethodVirtual call

Base Method call

Base MethodVirtual call

Base Method call

Base MethodVirtual call

Base Method call

TestShape End

TestDerive Start

Circle override MethodVirtual

Base Method call

Base MethodVirtual call

Base Method call

Triangle new MethodVirtual

Triangle new Method

Diamond default MethodVirtual

Diamond default Method

TestShape End

TestDerive2 Start

Circle override MethodVirtual

Base Method call

Base MethodVirtual call

Base Method call

Base MethodVirtual call

Base Method call

Base MethodVirtual call

Base Method call

TestDerive2 End

4. Poor records of a student

The video is not public. Contact www.zuikc.com ).

Scan, follow the most courses (www.zuikc.com), get more articles from me, and get the daily practice of software development.

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.