Deep understanding of OOP (first day): Polymorphism and inheritance (initial binding and compilation polymorphism), deep understanding of oop

Source: Internet
Author: User

Deep understanding of OOP (first day): Polymorphism and inheritance (initial binding and compilation polymorphism), deep understanding of oop

In this series, we mainly use the popular OOP blogs on CodeProject to provide in-depth and simple presentation of OOP.

As a master of software design or a cainiao, architecture design requires many restructures and trade-offs to facilitate the healthy construction of the entire software project. Some experiences are summarized by our predecessors, we can use it. Some of them are accumulated by team knowledge. In short, reusing the good ideas of our predecessors will help reduce rework. Of course, during the interview, if you can talk about OOP, you will naturally get a lot of extra points.

Start to read the preparatory knowledge of this series of blogs, such as polymorphism, encapsulation, and object-oriented programming. Please learn through MSDN. You should be familiar with such terms. This series of articles uses C # as the only programming language.

  • Deep understanding of OOP (1): Polymorphism and inheritance (polymorphism during initial binding and compilation)

  • Deep understanding of OOP (2): Polymorphism and inheritance (inheritance)

  • Deep understanding of OOP (III): Polymorphism and inheritance (dynamic binding and Runtime polymorphism)

  • Deep understanding of OOP (4): Polymorphism and inheritance (abstract class in C)

  • In-depth understanding of OOP (5): access modifier in C # (Public/Private/Protected/Internal/Sealed/Constants/Static and Readonly Fields)

  • Deep understanding of OOP (6): enumeration (practical method)

  • Deep understanding of OOP (7): attributes (practical methods)

  • Deep understanding of OOP (8): indexer (practical method)

  • Deep understanding of OOP (9): Events (in-depth understanding)

What is OOP and what are the advantages of OOP?

OOP stands for Object-Oriented Programming, which is based on the entire Object Programming and replaces the Programming idea based on process functions. The specific implementation is to encapsulate data and functions around objects, rather than based on logical relationships. Objects in OOP are directly connected to a specific type, or instance object of a certain type. More often, they are a class. Each class object has similar structures, but has its own unique attributes and data values. Objects can be accessed through external interfaces, such as methods and attributes. Based on these advantages of OOP, independent objects can be modified without affecting other objects, which makes it easier to upgrade software to reduce potential bugs. Software systems will become larger and larger over time. The OOP programming ideology effectively improves the readability and management of system code.

What is the concept of OOP?

The following five terms describe the concept of OOP:

  • Data Abstraction action): Data abstraction is the starting point for modeling objects to be operated. It not only abstracts the objects used, but also hides internal details (for end users ). You can easily use class methods and data without worrying about the complex processes behind data creation and running logic. Let's take the real world as an example. When you ride a bicycle, you don't have to consider how variable speed gears drive chains and wheels.
  • Inheritance)Inheritance is the most popular concept in OOP. Inheritance gives programmers the advantages of reusable code. The base class defines the function logic, and the subclass can be accessed directly through inheritance-just as convenient as the method of the subclass itself.
  • Data Encapsulation): Encapsulate the member variables and member functions of a class by using access controllers. This is called Data encapsulation. The access control operators include public, Protected, Private, and Internal.
  • Polymorphism): Objects can perform the same action by passing different parameters. This behavior is called polymorphism. Taking the real world as an example, the "Driving" method provides different parameters for different types of users to achieve polymorphism, such as Car. drive (Man), Car. drive (Woman) and so on.
  • Message Communication): Message communication means that class functions are called and executed through messages.
Polymorphism)

In this section, we use code snippets to illustrate the polymorphism types of each type: function overload, early binding, and compiler polymorphism.

Create a console project and name itInheritanceAndPolymorphism, and then add the classOverload. cs, And then addDisplayOverloadFunction.

public class Overload    {        public void DisplayOverload(int a){            System.Console.WriteLine("DisplayOverload " + a);        }        public void DisplayOverload(string a){            System.Console.WriteLine("DisplayOverload " + a);        }        public void DisplayOverload(string a, int b){            System.Console.WriteLine("DisplayOverload " + a + b);        }    }

InProgram. csAdd the following code:

class Program{        static void Main(string[] args)        {            Overload overload = new Overload();            overload.DisplayOverload(100);            overload.DisplayOverload("method overloading");            overload.DisplayOverload("method overloading", 100);            Console.ReadKey();        }}

Run the program. The result is as follows:

 DisplayOverload 100 
DisplayOverload method overloading 
DisplayOverload method overloading100

In the Overload classDisplayOverload provides three different types of overload functions: the method name is the same, and the parameter type and number are different. In C #, this method becomes an overload. We do not need to define a function with different names for each type of function, but only need to change the type and number of function parameters. This also becomes a function signature.

Can I use different return values? Let's try the following code:

public void DisplayOverload() { }public int DisplayOverload(){ }

Visual Studio returns the following error message:

 Error: Type 'InheritanceAndPolymorphism.Overload' already defines a member called 'DisplayOverload' with the same parameter types

From the above results, we can see that the returned value is not signed as a multi-state function.

Run the following code:

static void DisplayOverload(int a)  {   }public void DisplayOverload(int a) {   }public void DisplayOverload(string a){  }

The result is still an error:

Error: Type 'InheritanceAndPolymorphism.Overload' already defines a member called 'DisplayOverload' with the same parameter types

Conclusion: static visible function modifiers are not used as heavy-duty signatures.

Run the following code and try whether out and ref can be used as the reload signature.

private void DisplayOverload(int a) {   }private void DisplayOverload(out int a)        {            a = 100;        }private void DisplayOverload(ref int a) {   }

The result is the following error:

Error: Cannot define overloaded method 'DisplayOverload' because it differs from another method only on ref and out

Conclusion: The parameter modifiers passed by ref and out cannot be used as the reload signature.

Role of the Params parameter in Polymorphism

A function can contain the following four types of parameter passing:

  • Pass by value)
  • Pass by reference)
  • As an output parameter)
  • Use the parameter array (Using parameter arrays)

Run the following code:

public void DisplayOverload(int a, string a)  {   }        public void Display(int a)        {            string a;        }

Obtain the following error message:

Error1: The parameter name 'a' is a duplicate

Error2: A local variable named 'a' cannot be declared in this scope because it would give a different meaning to 'a', which is already used in a 'parent or current' scope to denote something else

In the same scope, the parameter name must be unique.

In the Overload. cs file, add the following code:

public class Overload    {        private string name = "Akhil";        public void Display()        {            Display2(ref name, ref name);            System.Console.WriteLine(name);        }        private void Display2(ref string x, ref string y)        {            System.Console.WriteLine(name);            x = "Akhil 1";            System.Console.WriteLine(name);            y = "Akhil 2";            System.Console.WriteLine(name);            name = "Akhil 3";        }    }

Add the following code to Program. cs:

class Program    {        static void Main(string[] args)        {            Overload overload = new Overload();            overload.Display();            Console.ReadKey();        }    }

The running result is as follows:

Akhil 
Akhil 1 
Akhil 2 
Akhil3

Conclusion: The memory address of name is passed through ref reference. Therefore, modifying the values of x and y is equivalent to directly modifying the value of name. Therefore, the result is run as above.

 

The following code demonstrates the role of the params Keyword:

Add the following code to the Overload. cs file:

public class Overload    {        public void Display()        {            DisplayOverload(100, "Akhil", "Mittal", "OOP");            DisplayOverload(200, "Akhil");            DisplayOverload(300);        }        private void DisplayOverload(int a, params string[] parameterArray)        {            foreach (string str in parameterArray)               Console.WriteLine(str + " " + a);        }    }

Add the following code to the Program. cs file:

class Program    {        static void Main(string[] args)        {            Overload overload = new Overload();            overload.Display();            Console.ReadKey();        }    }

The running result is as follows:

Akhil 100 
Mittal 100 
OOP 100 
Akhil 200

C # provides the params dynamic parameter array mechanism, which makes it easy to dynamically transfer different numbers of parameters of the same type during runtime.

Note: The params keyword can only be used as the last parameter of the function.

 

Let's try the priority order of the params keyword function signature and the non-params keyword function signature:

public class Overload    {        public void Display()        {            DisplayOverload(200);            DisplayOverload(200, 300);            DisplayOverload(200, 300, 500, 600);        }        private void DisplayOverload(int x, int y)        {            Console.WriteLine("The two integers " + x + " " + y);        }        private void DisplayOverload(params int[] parameterArray)        {            Console.WriteLine("parameterArray");        }    }

Add the following code to the Program. cs file:

class Program    {        static void Main(string[] args)        {            Overload overload = new Overload();            overload.Display();            Console.ReadKey();        }    }

The running result is as follows:

parameterArray 
The two integers 200 300 
parameterArray

According to the running results, C # takes precedence over precise matching of non-params functions. For example, if one int type or three int types are involved, the params type is used for matching; two int types, which are matched with well-defined functions.

 

Conclusion

In this section, the first part of the OOP series describes the polymorphism of the compiler, also known as early binding or method overloading. At the same time, we also learn the powerfulUse the params keyword to implement polymorphism.

The main points of this article are summarized as follows:

  • C # The function overload signature rules are determined by the parameter type and quantity, rather than the function name.
  • The Return Value of the function is not used as an overload signature.
  • Modifier is not part of the signature, such as static
  • In the same function, multiple parameter names must be unique
  • Ref and out are passed by reference, and the parameter memory address is passed.
  • As a parameter keyword, params can only be used for the last parameter of a function.

 

Address: http://www.codeproject.com/Articles/771455/Diving-in-OOP-Day-Polymorphism-and-Inheritance-Ear

Http://www.cnblogs.com/powertoolsteam/p/Diving-in-OOP-Day-Polymorphism-and-Inheritance-Ear.html.

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.