C # learning notes: Polymorphism and hiding, covering

Source: Internet
Author: User

Based on inheritance, the inheritance example is as follows:

Public   Class Person
{
 Public VoidSayhello ()
 {
Console. writeline ("Hello, I am a person");
}
}
Public   Class Student: person
{
}

 

Student class inheritance and person class

We want to change the sayhello () method inherited from student to have its own features. Here we use the new keyword.

Public   Class Person
{
 Public VoidSayhello ()
 {
Console. writeline ("Hello, I am a person");
}
}
Public   Class Student: person
{< br> New Public void sayhello ()
{< br> console. writeline ( " hello, I am a student " );
}
}

Public   Class Test
{
  Static   Void Main ()
  {
Person aperson=NewPerson ();
Student astudent= NewAstudent ();

Aperson. sayhello ();
Astudent. sayhello ();
}
}

Output:
Hello, I am a person
Hello, I am a student

This process is called override in inside C #-mspress:
You want to derive a class from (person) and you want to override the (sayhello) method to do something specific to the derived class. to do this, you need to use the new keyword with the derived class's method definition.
However, when translated into Chinese, it is called "hidden.

Polymorphism)

When you use the new keyword to override the method of the base class,ProgramThe operation is satisfactory.
(Method overriding with the New Keyword works fine if you have a reference to the derived object)

Every concept of a language is justified (you cannot ask yourself why C # has class, method...). Here, we want to ask:
Why is there the concept of polymorphism? What is the purpose?
(I read a lot of. net books, but I don't seem to have explained these concepts)

From the actual situation, let's look at the example below: student and teacher are all persons. In actual applications, we need to assemble all the derived classes of persons (populate) into an array, the data type of this array must be person, and the sayhello method of the array element (derived class of person) is re-called through this person [] array.

Public   Class Person
{
 Public VoidSayhello ()
 {
Console. writeline ("Hello, I am a person");
}
}
Public   Class Student: person
{< br> New Public void sayhello ()
{< br> console. writeline ( " hello, I am a student " );
}
}
Public   Class Teacher: person
{< br> New Public void sayhello ()
{< br> console. writeline ( " hello, I am a teacher " );
}
}
Public   Class Test
{
  Private   Static Person [] persons = New Person [ 2 ];
  Static   Void Main ()
  {
Persons [0]=NewStudent ();
Persons [1]=NewTeacher ();
 
Persons [0]. Sayhello ();
Persons [1]. Sayhello ();
}
}

Input result:
Hello, I am a person
Hello, I am a person

(Obviusly, this is not what we wanted). In actual applications, we do not want this result.
Expected output:
Hello, I am a student
Hello, I am a teacher

In the above example, why is the result we don't want?
Let's take a look at the description of Inside C:

What happened here is an example of a phenomenon called early binding. when the code was compiled, the C # compiler looked at the call to persons []. sayhello () and determined the address in memory that it wowould need to jump to when the call is made. in this case, that wocould be the memory location of the person. sayhello method.
Take a look at the following msil that was generated from the test application, and specifically take note of line il_0014 and the fact that it explicitly CILS the employee. calculatepay method:

....
Il_0014: Call instance void EMPLOYEE: calculatepay ()

....

that call to the (person. sayhello) method is the problem. what we want instead is for late binding to occur. late binding means that the compiler does not select the method to execute until run time. to force the compiler to call the correct version of an upcasted object's method, we use two new keywords: Virtual and override. the virtual keyword must be used on the base class's method, and the override keyword is used on the derived class's implementation of the method.

public class person
{< br> virtual public void sayhello ()
{< br> console. writeline ("Hello, I am a person");
}< br> public class student: person
{< br> override public void sayhello ()
{< br> console. writeline ("Hello, I am a student");
}< br> public class teacher: person
{< br> override public void sayhello ()
{< br> console. writeline ("Hello, I am a teacher ");
}< BR >}< br> public class test
{< br> Private Static person [] persons = new person [2];
static void main ()
{< br> persons [0] = new student ();
persons [1] = new teacher ();
persons [0]. sayhello ();
persons [1]. sayhello ();
}< BR >}

Before running this application, let's take a peek at the Il code that's generated, this time noting that line il_0014 uses the msil opcode callvirt, which tells the compiler that the exact method to be called won't be known until run time because it's dependent on which derived object is being used:

.....
Il_0014: callvirt instance void EMPLOYEE: calculatepay ()
.....

Output:
Hello, I am a student
Hello, I am a teacher

To deeply understand this process, you must understand what is "Early binding & late binding", "Run Time", and have knowledge about "compilation principles.
I have not learned "compilation principles" and "assembler" yet. This is still not thorough and I will not reference this information. Please refer to the msdn

BTW, we can also use type conversion to get what we want:
Modify class test:

Public   Class Test
{
  Private   Static Person [] persons = New Person [ 2 ];
  Static   Void Main ()
  {
Persons [ 0 ] = New Student ();
Persons [ 1 ] = New Teacher ();
 
Student s = New Student ();
Teacher t = New Teacher ();

S = (Student) persons [ 0 ];
T = (Teacher) persons [ 1 ];

S. sayhello ();
T. sayhello ();

}
}

========================================================== ===
AboveArticleReference (some words are for direct translation)
[1] inside C #/Tom Archer. (Microsoft Press)
[2] Visual C #. Net: A gudie for VB6 develops/brand Maiani, James still... (wrax)

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.